What is a class of type "class MyClassExampleT where T: new () {}"?

3

Is a class ExemploClass<T> class a list? See the example class below:

public abstract class MinhaClasseExemplo<T> where T: new()
{
   public T value {get; set;}
}

What does each part of this expression mean: abstract class MinhaClasseExemplo<T> , where , T , : and new() and what is the purpose of a class of this type?     

asked by anonymous 04.01.2016 / 02:12

1 answer

4

Probably not a list. It's any data structure. It could be if I had other parts that would indicate this.

abstract means that the class is abstract . It can not be instantiated, it can only be used as a parent of another inheritance class.

<T> is used to indicate what the generic type will be. It is a kind of super variable that will be replaced by a real type when the class is instantiated. It is used to get type generability in classes and methods . So the class can work with several different types safely from the point of view of types, which is great in languages that value by static types. So in this example, if the instance is MinhaClasseExemplo<string> , the property in the instance looks like this: public string value {get; set;} . It is a way to use the same class for many types without having to write a version for each type.

where T: new() is a restriction than T can be, in case, it will only accept types that have a default constructor . In this particular case it is a convention to say that new() is this requirement. Some problems could occur if you do not have a restriction. After all the operation that will be executed within the class with this type may require a particular resource. Without the restriction a type could be used that does not have the expected resource and would not work. Obviously the compiler already takes this error and does not even let it use any kind. When you restrict which types can be used, it is guaranteed that they can be used. On the documentation page you can see other forms of restriction that can be used.

In this specific example the only thing I can say about the class is that it will be used as the basis for another class and that parts of it can have its type set according to instantiation. Any other information would be speculation.

    
04.01.2016 / 02:27