Reputation: 12338
I have the following example code. Why do I have to specify a type for T? Is this something that I can take advantage of? I do not see why the enum definition is depending on the type argument? How can the contents of the enum be something else depending on the type? So in my syntactic sugar favor I would like to leave the definition of the type out.
public class SomeGenericClass<T>
{
public enum InitialisationMode
{
UseDefaultValues,
DoOtherThings
}
public SomeGenericClass(InitialisationMode initMode = InitialisationMode.UseDefaultValues)
{
}
}
public class SomeOtherClass
{
public void DoAction()
{
//Why do I have to specify the generic type arguments when using the enum value?
var genericClass = new SomeGenericClass<int>(SomeGenericClass<int>.InitialisationMode.DoOtherThings);
//I Would expect to be able to use the enum like the line below:
genericClass = new SomeGenericClass<int>(SomeGenericClass.InitialisationMode.DoOtherThings);
}
}
I know I could workd around this by doing something like this, or put the enum one scope up:
public class SomeGenericClass<T>
{
public SomeGenericClass(SomeGenericClass.InitialisationMode initMode = SomeGenericClass.InitialisationMode.UseDefaultValues)
{
}
}
public abstract class SomeGenericClass
{
public enum InitialisationMode
{
UseDefaultValues,
DoOtherThings
}
}
public class SomeOtherClass
{
public void DoAction()
{
//I Would expect to be able to use the enum like the line below:
var genericClass = new SomeGenericClass<int>(SomeGenericClass.InitialisationMode.DoOtherThings);
}
}
Upvotes: 3
Views: 151
Reputation: 21661
Because your enum lives in that class, and it would be possible (if not very practical) to have that enumeration be different for different types:
class Program
{
static void Main(string[] args)
{
var sgc = new SomeGenericClass<string>("asdf");
var sgc2 = new SomeGenericClass<int>(1);
var sgc3 = new SomeNonGenericChild("asdf2");
Console.ReadKey();
}
}
public class SomeGenericClass<T>
{
public enum InitialisationMode
{
UseDefaultValues,
DoOtherThings = 3
}
public SomeGenericClass(T blah, InitialisationMode initMode = InitialisationMode.UseDefaultValues)
{
Console.WriteLine(blah.GetType().Name + "; " + initMode);
}
}
public class SomeNonGenericChild : SomeGenericClass<string>
{
public new enum InitialisationMode
{
UseDefaultValues,
DoEvenMoreThings
}
public SomeNonGenericChild(string blah, InitialisationMode initMode= InitialisationMode.DoEvenMoreThings) : base(blah)
{
Console.WriteLine(blah.GetType().Name + "; " + initMode);
}
}
To achieve the syntax you want, you could do something like:
namespace SomeNamespace
{
public enum InitialisationMode
{
UseDefaultValues,
DoOtherThings
}
public class SomeGenericClass<T>
{
public SomeGenericClass(InitialisationMode initMode = InitialisationMode.UseDefaultValues)
{
}
}
}
Upvotes: 4