This question already has answers here:
What is the <T> in Cast<T>() or List<T> in C#
(2 answers)
Closed 2 years ago.
I'm new into c# and I see a lot of things like System.Span<T>, System.Memory<T>, Span<T>, Memory<T>, System.Collections.Generic.IEnumerable<T> etc. in the C# documentation.
Can somebody please explain what <T> is?
Any help is appreciated.
Check Generic Parameters
In a generic type or method definition, a type parameter is a placeholder for a specific type that a client specifies when they create an instance of the generic type. A generic class, such as GenericList<T> listed in Introduction to Generics, cannot be used as-is because it is not really a type; it is more like a blueprint for a type. To use GenericList<T>, client code must declare and instantiate a constructed type by specifying a type argument inside the angle brackets. The type argument for this particular class can be any type recognized by the compiler. Any number of constructed type instances can be created, each one using a different type argument, as follows:
For instance:
GenericList<float> list1 = new GenericList<float>();
GenericList<ExampleClass> list2 = new GenericList<ExampleClass>();
GenericList<ExampleStruct> list3 = new GenericList<ExampleStruct>();
In each of these instances of GenericList, every occurrence of T in the class is substituted at run time with the type argument. By means of this substitution, we have created three separate type-safe and efficient objects using a single class definition. For more information on how this substitution is performed by the CLR
In addition to the above, you can also have constraints about the type that T can be.
Related
This question already has answers here:
What does "where" mean in a C# class declaration?
(9 answers)
Closed 8 years ago.
I'm doing some Pluralsight training. The instructor specified several function declarations in an interface, one of which looks like this:
void Add<T>(T entity) where T : class;
So generics are being used, the data type is of type "T", it's declaring a parameter named "entity" which is of type T. What I don't understand if the clause:
"where T : class"
What does that mean?
This is called a generic constraint. It means that the type of T must be a class.
It's ensuring that the generic type T is of type class.
So as an example yourClass.Add<int>(2) would show a compile time error because int is not a class/reference type.
it is a constraint which says your T should be a reference Type.
From MSDN: where T : class
The type argument must be a reference type; this applies also to any
class, interface, delegate, or array type.
I am new to .NET C# and I was reading the code below:
var model = new TenantPageViewData<Tenant>(contentModel)
I can't understand <MyClass>, What does it mean to put <> in the code.
Also if you can guide me to documentation regarding this it will be great.
That is the syntax for specifying the type parameter for an open generic type. You can read more about generics here:
http://msdn.microsoft.com/en-us/library/512aeb7t.aspx
If you are new to C#, it will seem complicated at first, but a lot of the language makes use of this feature so it will be time very well spent learning it.
With the general documentation and answer out of the way, in this specific case, the TenantPageViewData exposes a generic parameter. You read that as "a TenantPageViewData<> of Tenant".
The signature for that class will look something like:
public class TenantPageViewData<T>
{
}
Where T is simply a placeholder you can reference in code that will, at compile-time, become strongly-typed to the type of argument you specify.
This class definition can be referred to as an "open" generic type because the placeholder T is, as yet, unrealised. The declaration var something = new TenantPageViewData<Tenant>() is a "closed" generic type because the generic argument is known to now be Tenant in this instance.
Type identity is per closed generic type, so a TenantPageViewData<Tenant> is not a TenantPageViewData<Landlord>, and static members of a generic class honour this also (which is a common pitfall of learning generics).
Other examples include List<string> usually read as "a List<> of string", and the comical Cup<T> :-)
these type of brackets I believe are used for marking generics.
http://msdn.microsoft.com/en-us/library/ms379564(v=vs.80).aspx
In C#, the angle brackets (< and >) are most often used to enclose a parameter of a generic class. For example, the .Net framework provides a List class where 'T' denotes the type of objects that will be contained in the list. Therefore, when the list is created as
List<string> myList = new List<string>();
you are creating a usable, type-safe instance of the List class.
Some good info on it here.
I would like to create the following class snippet
class Lookup<TKey,TValue,TCollection>
where TCollection : ICollection<>
{
public TCollection<TKey> _KeyCollection;
public TCollection<TValue> _ValueCollection;
}
Is this pattern in general possible in C#? In the current form the compiler does not like it. You can't seem to constrain a type parameter to be a generic. However it looks like it a reasonable thing to want to do. Is there any trick to achieve it?
Note: This question is specifically about generics and type constraints. It is not looking for a work around for what you think I might be trying to do in my wider application.
You can't constrain a generic type parameter to be an open generic type, which seems to be how you're attempting to use it in the rest of the class.
You asked for a spec reference, and there's not one place that seems to spell it out in a nice, concise manner.
The best I can find is in section 4.5 (from C# 5.0 spec):
As a type, type parameters are purely a compile-time construct. At run-time, each type parameter is bound to a run-time type that was specified by supplying a type argument to the generic type declaration. Thus, the type of a variable declared with a type parameter will, at run-time, be a closed constructed type (§4.4.2). The run-time execution of all statements and expressions involving type parameters uses the actual type that was supplied as the type argument for that parameter.
But in your attempt, TCollection won't match up with this text because it's asking for an non-closed type.
You can't have an open generic type as a constraint. You can, however, have a closed generic type:
class Lookup<TKey, TValue, TKeyCollection, TValueCollection>
where TKeyCollection : ICollection<TKey>
where TValueCollection : ICollection<TValue>
{
public TKeyCollection _KeyCollection;
public TValueCollection _ValueCollection;
}
It may not be pretty and there are a lot of type parameters, but it is possible.
example:
public event Action<List<WKSProfile>> WorkstationProfileChanged;
I have trouble understanding the the above member.
Does it imply that it returns :
Action<List<WKSProfile>>
This is the syntax to specify generic type parameters.
In a generic type or method definition, a type parameters is a placeholder for a specific type that a client specifies when they instantiate a variable of the generic type. A generic class, such as GenericList<T> listed in Introduction to Generics (C# Programming Guide), cannot be used as-is because it is not really a type; it is more like a blueprint for a type. To use GenericList<T>, client code must declare and instantiate a constructed type by specifying a type argument inside the angle brackets.
This question already has answers here:
If A<T1,T2> is a template for actual type, then why is typeof(A<,>) allowed?
(3 answers)
Closed 9 years ago.
I have some confusion with this that arose from messing around with exporting generic types in MEF
I noticed:
new Dictionary<string,bool>().GetType() == typeof(Dictionary<,>)
false
new Dictionary<string,bool>().GetType().GetGenericTypeDefinition() == typeof(Dictionary<,>)
true
Yet Dictionary<,> itself is not considered a ‘type’ as this will actually generate a compile error:
new Dictionary<string,bool> as Dictionary<,>
Type expected
new Dictionary<string,bool> is Dictionary<,>
Type expected
So my question is, is Dictionary<,> actually a type? Does .NET treat generic types differently than non-generic types?
Now in MEF I can export a generic class as
[Export(typeof(MyGenericClass<,>))]
And this would satisfy an import requirement like
[Import]
public MyGenericClass<string, long> Instance { get; set; }
I'm confused about the type-system's rules here
See What exactly is an “open generic type”. What you are referring to is called an unbound generic type and is explained in the same post. An unbound generic type is actually a type, however it can only be used within a typeof() expression. Note: Unlike C# Java allows expressions like List<?>.
Yes, MyType<,> is a type.
It's a "open generic" Type, See What exactly is an "open generic type" in .NET?