Is there a syntax trick to get to the constant in a generic class without specifying an (ad-hoc) type?
public class MyClass<T>{
public const string MyConstant = "fortytwo";
}
// I try to avoid this type specification.
var doeswork = MyClass<object>.MyConstant;
// Syntax similar to what I'd like to accomplish.
var doesnotwork = MyClass.MyConstant;
There is a caveat about the static variable (constant) not being shared between different types like MyClass<object>
and MyClass<int>
but my question is about possible available syntax trick.
Using generics, type parameters are not allowed to be static.
The const keyword converts nothing more but a constant. The specialty of these variables is that they need to have a value at compile time and, by default, they are static. This default value means that a single copy of the variable is created and shared among all objects.
In c#, generics are used to define a class or structure or methods with placeholders (type parameters) to indicate that they can use any of the types. Following is the example of defining a generic class with type parameter (T) as a placeholder with an angle (<>) brackets.
A const object is always static . const makes the variable constant and cannot be changed.
Use a non-generic abstract parent class.
public abstract class MyClass
{
public const string MyConstant = "fortytwo";
}
public class MyClass<T> : MyClass
{
// stuff
}
var doeswork = MyClass.MyConstant;
That of course assumes that there's some reason the constant needs to be part of the generic class; if it has public accessibility, I'm not seeing a reason why you wouldn't just put it in a separate class.
Having a non-generic abstract parent class is a good idea for every generic class you make; the generic class is actually a template for the specific subtype classes, rather than a true parent, so having a true non-generic parent can make some techniques (such as, but certainly not limited to, this one) a lot easier.
Something like this works:
using System;
namespace Demo
{
public class MyClass // Use a non-generic base class for the non-generic bits.
{
public const string MyConstant = "fortytwo";
public static string MyString()
{
return MyConstant;
}
}
public class MyClass<T>: MyClass // Derive the generic class
{ // from the non-generic one.
public void Test(T item)
{
Console.WriteLine(MyConstant);
Console.WriteLine(item);
}
}
public static class Program
{
private static void Main()
{
Console.WriteLine(MyClass.MyConstant);
Console.WriteLine(MyClass.MyString());
}
}
}
This approach works for any static types or values that you want to provide which do not depend on the type parameter. It also works with static methods too.
(Note: If you don't want anybody to instantiate the base class, make it abstract.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With