Public static (const) in a common .NET class

Is there a syntax trick to jump to a constant in a generic class without specifying a type (ad-hoc)?

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 that a static variable (constant) is not shared between different types such as MyClass<object> and MyClass<int> , but my question is about a possible syntax trick.

+6
source share
2 answers

Use a parent parent class that is not shared.

 public abstract class MyClass { public const string MyConstant = "fortytwo"; } public class MyClass<T> : MyClass { // stuff } var doeswork = MyClass.MyConstant; 

This, of course, suggests that there is some reason why a constant should be part of a universal class; if it has public accessibility, I see no reason why you would not just put it in a separate class.

Having a non-core abstract parent class is a good idea for every class you generate; a generic class is actually a template for certain classes of subtypes, and not for a true parent, so having a true parent other than a parent can greatly facilitate some methods (for example, but not limited to).

+11
source

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 that are independent of the type parameter. It also works with static methods.

(Note: If you do not want anyone to instantiate the base class, make it abstract.)

+5
source

Source: https://habr.com/ru/post/980704/


All Articles