user469652
user469652

Reputation: 51221

c# syntax help -> What does Get<T>() where T means

public static T Get<T>() where T : class
{
    string implName = Program.Settings[typeof(T).Name].ToString();
    object concrete = Activator.CreateInstance(Type.GetType(implName));

    return (T)concrete;
}

Please explain what does Get() where T means?

Welcome to put some reading URLs.

Upvotes: 2

Views: 2661

Answers (3)

Razor
Razor

Reputation: 17498

This will constrain T to be a reference type in this particular case.

Upvotes: 1

Pauli &#216;ster&#248;
Pauli &#216;ster&#248;

Reputation: 6916

The where T : class puts a constrain on what types are allowed for T. This will

  1. Give you an compiler error if you put in a wrong type
  2. Give you access to access methods/properties or instantiate instances of T based on the constraint

So for your method this will produce an error if you call it like this Get<int>() since int is not a class.

public static T Get<T>() where T : class
{
    string implName = Program.Settings[typeof(T).Name].ToString();
    var implType = Type.GetType(implName);

    return (T)Activator.CreateInstance(implType);
}

Upvotes: 3

Randy Minder
Randy Minder

Reputation: 48402

This is an example of a generic. 'T' represents a type.

For example:

string result = Get<string>();

Do a Google search on Generics. This will get you started: http://msdn.microsoft.com/en-us/library/ms379564(v=vs.80).aspx

Upvotes: 2

Related Questions