What is a type class "class Minhaclasseexample<T> Where T: new(){}"?

Asked

Viewed 452 times

8

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

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

Which means every part of this expression: abstract class MinhaClasseExemplo<T>, where, T, : and new() and what is the purpose of such a class?

1 answer

7


It’s probably not a list, it’s some sort of data structure, it could be if there were other parts that indicate that.

The abstract means that the class is abstract. She cannot be instantiated, she can only be used as the mother of another class in inheritance.

<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 obtain type genericity in classes and methods. So the class can work with several different types safely from a type point of view, which is great in languages that value static types.

So in this example, if the instance is MinhaClasseExemplo<string>, the property in the instance would look like this: public string value {get; set;}. It is a way to use the same class for several types without having to write a version for each type.

The where T: new() is a restriction than the T may be, in case he will only accept types that have a standard builder. In this particular case it is a convention to say that new() is that 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 certain resource. Without the restriction could be used a type that does not have the expected resource and would not work. Obviously the compiler already picks up this error and doesn’t even let it use any type. 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 particular example the only thing I can say about the class is that it will be used as a basis for another class and what parts of it may have its type defined according to the instantiation. Any other information would be speculation.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.