I can work around this, but I am curious why it won’t work:
In the same way that you can create an optional parameter with a default value for a routine, such as the one below…..
public void SomeRoutine(string Title = "Missing")
{
// Do something with Title
}
…. why can’t you assign a default Type as an optional parameter ?
The following example gives the error: “Default Parameter For ‘theType’ must be a compile time constant.”
public void SomeOtherRoutine(Type theType = typeof(MyClass))
{
// Do something based on theType
}
The actual application is trying to do provide the option for enumerating a collection that contains a mix of base and various derived classes, and returning only the class type of interest:
public IEnumerable<MyBaseClass> EnumerateWithOptions(Type optionalDerivedClass = typeof(MyBaseClass))
{
foreach (MyBaseClass thingy in MyCustomCollection())
{
if (thingy.GetType() == optionalDerivedClass)
{ yield return thingy; };
}
}
The obvious alternative is to overload the routine to apply the default value as shown below, however it is not ideal in my app for reasons that are not worth trying to describe.
public IEnumerable<MyBaseClass> EnumerateWithOptions()
{
return EnumerateWithOptions(typeof(MyBaseClass));
}
public IEnumerable<MyBaseClass> EnumerateWithOptions(Type optionalDerivedClass)
{
foreach (MyBaseClass thingy in MyCustomCollection())
{
if (thingy.GetType() == optionalDerivedClass)
{ yield return thingy; };
}
}
Any ideas why typeof(MyClass) is not considered a compile time constant, or any ideas for a different approach ? Thanks.
Thus you cannot use
typeofor someTypevalue, and you don’t want to create overload manually, then consider providenullas default value for optional parameter:If it is possible for you to use generic parameter instead of
Typeobject, then you can filter collection viaEnumerable.OfType<T>():