As far as I know you can can't pass parameters to a static constructor in C#.
However I do have 2 parameters I need to pass and assign them to static fields before I create an instance of a class. How do I go about it?
This may be a call for ... a Factory Method!
class Foo
{
private int bar;
private static Foo _foo;
private Foo() {}
static Foo Create(int initialBar)
{
_foo = new Foo();
_foo.bar = initialBar;
return _foo;
}
private int quux;
public void Fn1() {}
}
You may want to put a check that 'bar' is already initialized (or not) as appropriate.
You can't pass parameters to a static constructor, but you can pass parameters to the class itself - via generic type parameters.
Slightly crazy this idea, however, I'll just throw it out there anyway.
Make the class generic (with a TypeParam that will provide a parameter type) and place generic constraints on it (details in code example), then derive a new parameter type, which contains virtuals that you can use to read what they want the parameter values to be.
//base parameter type - provides the 'anchor' for our generic constraint later,
//as well as a nice, strong-typed access to our param values.
public class StaticParameterBase
{
public abstract string ParameterString{ get; }
public abstract MyComplexType ParameterComplex { get; }
}
//note the use of the new() generic constraint so we know we can confidently create
//an instance of the type.
public class MyType<TParameter> where TParameter:StaticParameterBase, new()
{
//local copies of parameter values. Could also simply cache an instance of
//TParameter and wrap around that.
private static string ParameterString { get; set; }
private static MyComplexType ParameterComplex { get; set; }
static MyType()
{
var myParams = new TParameter();
ParameterString = myParams.ParameterString;
ParameterComplex = myParams.ParameterComplex;
}
}
//e.g, a parameter type could be like this:
public class MyCustomParameterType : StaticParameterBase
{
public override string ParameterString { get { return "Hello crazy world!"; } }
public override MyComplexType { get {
//or wherever this object would actually be obtained from.
return new MyComplexType() { /*initializers etc */ };
}
}
}
//you can also now derive from MyType<>, specialising for your desired parameter type
//so you can hide the generic bit in the future (there will be limits to this one's
//usefulness - especially if new constructors are added to MyType<>, as they will
//have to be mirrored on this type as well).
public class MyType2 : MyType<MyCustomParameterType> { }
//then you'd use the type like this:
public static void main()
{
var instance = new MyType<MyCustomParameterType>();
//or this:
var instance2 = new MyType2();
}
I did consider a solution that employs custom type attributes applies to a type parameter, however this is easily a better way. However, you'll now be using your class always with a generic parameter type (unless you can use the deriving+specialisation trick) - possibly too clumsy for your liking.
I'd also prefer this over the other solutions presented here as it doesn't require creating any workarounds for the static initialisation - you can still use .Net's guarantee of single-time initialisation.
A word of warning - should you be reviewing your structure?
All that said - remember, though, since you can only parameterise the static once (or in this case, each uniquely parameterised static generic) - I would be asking myself why not just pull the code that is getting the parameters to give to the static, and place it in the static constructor in the first place? That way you don't actually have to resort to strange patterns like this!
I assume you mean static members of a class? In that case, you can do this:
public class MyClass
{
public static int MyInt = 12;
public static MyOtherClass MyOther = new MyOtherClass();
}
Those static members are guaranteed to be instantiated before any class is instantiated.
If you need complex logic, do it in a static constructor:
public class MyClass
{
public static int MyInt;
public static MyOtherClass MyOther;
static MyClass()
{
MyInt = 12;
MyOther = new MyOtherClass();
}
}
Edit
Based on your edit, I'd say just assign the values to what they need to be before you instantiate the class, like so:
public class MyClass
{
public static int MyInt;
public static MyOtherClass MyOther;
}
// elsewhere in code, before you instantiate MyClass:
MyClass.MyInt = 12;
MyClass.MyOther = new MyOtherClass();
MyClass myClass = new MyClass();
That said, this method gives you no guarantee that MyInt and MyOther are set before MyClass is instantiated. It will work, but requires discipline before instantiating MyClass.
One alternative pattern you might follow looks like this:
public class MyClass
{
private static int MyInt;
private static MyOtherClass MyOther;
private static bool IsStaticInitialized = false;
public static InitializeStatic(int myInt, MyOtherClass other)
{
MyInt = myInt;
MyOther = other;
IsStaticInitialized = true;
}
public MyClass()
{
if(!IsStaticInitialized)
{
throw new InvalidOperationException("Static Not Initialized");
}
// other constructor logic here.
}
}
// elsewhere in your code:
MyClass.InitializeStatic(12, new MyOtherClass());
MyClass myClass = new MyClass();
// alternatiavely:
MyClass myClass = new MyClass(); // runtime exception.
Related
Suppose I had a class with static members of itself, just like a singleton.
I also allow the construction of that class.
If a consumer constructs with known arguments I want to return a static member instead of a new construction.
Below is non compiling example code that illustrates the point.
Essentially I want the class to be constructed like illustrated in the Construct method but I do not want the consumer of the class to be forced into rewriting his existing new MyClass(0) calls.
Is that possible?
public class MyClass
{
public static readonly MyClass Zero = new MyClass(0);
private int n;
public static MyClass Construct(int n)
{
MyClass self = new MyClass(0, true); //the bool just helps with referencing
ReplaceIfZero(ref self);
return self;
}
public MyClass(int n, bool x) //the bool is just so i can reference it in this example
{
this.n = n;
}
public MyClass(int n)
{
this.n = n;
ReplaceIfZero(ref this);
// Error CS1605 Cannot pass 'this' as a ref or out argument because it is read - only
}
ReplaceIfZero(ref MyClass myclass)
{
if(Zero.Equals(myclass))
{
myclass = Zero;
}
}
public override bool Equals(object obj)
{
return ReferenceEquals(this, obj) || ( (obj is MyClass) && n.Equals((obj as MyClass).n) );
}
}
The normal solution to this is to make the constructor private and add a public static factory method that takes care of things. I think that would be the best approach.
However, another approach is the use an interface and a wrapper class to hide away the details.
Something like this:
public interface IMyClass
{
int SomeMethod(int x);
}
public class MyClass: IMyClass
{
public MyClass(int n)
{
_impl = MyClassImpl.Create(n);
}
public int SomeMethod(int x)
{
return _impl.SomeMethod(x);
}
// For test purposes only - see later in this answer.
public bool ImplementationEquals(MyClass other)
{
return ReferenceEquals(_impl, other._impl);
}
readonly IMyClass _impl;
}
internal class MyClassImpl : IMyClass
{
static readonly ConcurrentDictionary<int, IMyClass> _dict = new ConcurrentDictionary<int, IMyClass>();
readonly int _n;
MyClassImpl(int n)
{
_n = n;
}
public static IMyClass Create(int n)
{
return _dict.GetOrAdd(n, i => new MyClassImpl(i));
}
public int SomeMethod(int x)
{
return _n + x;
}
}
Then client code can create instances of MyClass, and behind the scenes another class is used for the implementation.
If the client code creates two instances of MyClass, the implementing object will be shared, as this code demonstrates:
var a = new MyClass(1);
var b = new MyClass(2);
var c = new MyClass(1);
Console.WriteLine(a.ImplementationEquals(b)); // Prints false
Console.WriteLine(a.ImplementationEquals(c)); // Prints true
Also note that if you do something like this, it's very important that the class is strongly immutable (i.e. all of its fields are immutable, and if a field is not a primitive type, all of its fields are recursively immutable)
As I mentioned in the comments, C# does not allow you to change the result of the new operator. It always returns a new instance of class. Of course we are speaking about normal classes and not special hacks like ContextBoundObject and proxies.
So there is no way to keep your clients using the new operator and get the desired behavior. You need to remove the public constructors and force your clients to use some public static factory method like MyClass.Create (or Construct as in your example).
As far as I understand from your code, You want to provide the same object if user creates the same number for another instance. If then it is better to user factory pattern or singleton pattern
Well, you seem to want only one instance of your class.
Would be easier to create a static class, no ?
public static class MyClass
{
static MyClass()
{
n_ = 2;
}
private static int n_;
public static void Construct(int number)
{
n_= number;
}
}
I have a few classes. Lets say:
public class A
{
public void SomeAction()
{
Debug.Write("I was declared in class: and my name is:");
}
}
And
public class B
{
public static A myClass = new A();
}
public class C
{
public static A myClass = new A();
}
public class D
{
public static A myClass = new A();
}
What I want "SomeAction" in class A to do is to print out which class it was initialized in.
So that for example in another class I called C.myClass.SomeAction(); it would print out "I was declared in class C my name is myClass"
I hope this makes sense.
The reasons im doing this is for debugging within automated testing. I understand its not the best way to do things but its a requirement of the business.
This requirement can be satisfied without inheritance or passing the object; we can get the name of the class that calls the constructor from within the body of the constructor by examining the stack.
public class A
{
private string _createdBy;
public void SomeAction()
{
Console.WriteLine("I was declared in class [{0}]", _createdBy);
}
public A()
{
var stackFrame = new StackFrame(1);
var method = stackFrame.GetMethod();
_createdBy = method.DeclaringType.Name;
}
}
In terms of performance, I am assuming that you are not creating many instances of these objects. You could also predicate this on whether you are doing a DEBUG build or on some other setting, so that this stuff is skipped entirely in your production executables.
Since you only reference an instance of class A in your other classes, I think there is no other way then setting a reference to the type which created class A, like eddie_cat already mentioned. You could do something like this:
public class B
{
public static A myClass = new A(typeof(B));
}
And then your class A would look like:
public class A
{
// store the parent type
private Type mParentClass;
// provide parent type during construction of A
public A(Type parentClass)
{
mParentClass = parentClass;
}
// note that method cannot be static anymore, since every instance of A might
// have a different parent
public void SomeAction()
{
// access field where parent type is stored.
Debug.Write("I was declared in class: {0} and my name is:",mParentClass.Name);
}
}
I think you have two choices. Either set a property in A, or inherit from A. Personally, I prefer inheriting from A, because then A could just use GetType().
public class A
{
public void SomeMethod()
{
Debug.Write(string.Format("I was declared in class: {0}",this.GetType()));
}
}
public class B : A
{
}
var instanceOfB = new B();
instanceOfB.SomeMethod();
This is a followup to a previous question. There was a mistake in that question (I actually posted my current solution instead of the better one I'm looking for).
I have 3 classes, ParentClass,ClassA,ClassB. Both ClassA and ClassB are subclasses of ParentClass. I wanna try to create objects of type ClassA or ClassB using some kind of enumeration to identify a type, and then instantiate the object cast as the parent type. How can I do that dynamically? Please take a look at the code below, and the part that says //what do I put here?. Thanks for reading!
public enum ClassType
{
ClassA,
ClassB
};
public abstract class ParentClass
{
public static readonly Dictionary<ClassType, Type> Types =
new Dictionary<ClassType, Type>{
{ClassType.ClassA, typeof(ClassA) },
{ClassType.ClassB, typeof(ClassB) }
};
public ParentClass()
{
//....
}
public static ParentClass GetNewObjectOfType(ClassType type)
{
//What do I put here?
}
}
public class ClassA:ParentClass
{
//....
}
public class ClassB:ParentClass
{
//.......
}
You can do it easily with the Activator class, especially if there aren't any arguments to the constructors:
return Activator.CreateInstance(Types[type]);
To restate your question: you're looking for advice on how to code a static factory method.
I don't think you need a separate enumeration to accomplish this. This is a LINQPad script I threw together (EDIT: added static constants, demo creation using them)
void Main()
{
var a = ParentClass.Create(typeof(ClassA));
var b = ParentClass.Create(typeof(ClassB));
var c = ParentClass.Create(ParentClass.ClassAType);
a.Dump();
b.Dump();
c.Dump();
}
public abstract class ParentClass
{
public static readonly Type ClassAType = typeof(ClassA);
public static readonly Type ClassBType = typeof(ClassB);
public string SomeProp { get; set; }
protected ParentClass() {}
public static ParentClass Create(Type typeToCreate)
{
// validate that type is derived from ParentClass
return (ParentClass)Activator.CreateInstance(typeToCreate);
}
}
public class ClassA:ParentClass {
public ClassA()
{
SomeProp = "ClassA~";
}
}
public class ClassB:ParentClass
{
public ClassB()
{
SomeProp = "ClassB~";
}
}
As stated in the previous question:
Reflection is slow and is often used where it isn't needed
Activator.CreateInstance uses reflection to track down a parameter-less constructor. To solve this problem - that isn't needed. The parent class already knows all of the types it is responsible for creating.
One of the reasons to use a static factory method, is that there may be substantial work, or different kinds of work involved in creating the child classes. I think if you beef up your map some, you'll have a easier time coding that static factory:
public static readonly Dictionary<ClassType, Func<ParentClass>> Types =
new Dictionary<ClassType, Func<ParentClass>>{
{ClassType.ClassA, () => new ClassA(1, 2, 3) },
{ClassType.ClassB, () => new ClassB("1") }
};
public static ParentClass GetNewObjectOfType(ClassType type)
{
Func<ParentClass> maker = Types[type];
ParentClass result = maker();
return result;
}
Problem
I am working with an already existing library, to the source code of which I do not have access. This library represents an AST.
I want to copy parts of this AST, but rename references to variables in the process. Since there can be a AssignCommand-Object, which holds an Expression-object, I want to be able to copy each object with its own function, so I can call them recursively. However, since I do not have access to the code of the library, I cannot add a method such as CopyAndRename(string prefix).
Thus, my approach was to create a single function Rename with several overloads. Thus, I would have a family functions as follows:
public static Command Rename(Command cmd, string prefix)
public static AssignCommand Rename(AssignCommand cmd, string prefix)
public static AdditionExpressionRename(AdditionExpression expr, string prefix)
....
A function now consists of a List<Command>, where AssignCommand is a subclass of Command. I assumed that I could just pass a Command to the Rename-function and the runtime would find the most specific one. However, this is not the case and all commands are passed to Command Rename(Command cmd, string prefix). Why is this the case? Is there a way to delegate the call to the correct function without using ugly is-operations?
Minimal Example
I have broken this problem down to the following NUnit-Testcode
using NUnit.Framework;
public class TopClass{
public int retVal;
}
public class SubClassA : TopClass{ }
[TestFixture]
public class ThrowawayTest {
private TopClass Foo (TopClass x) {
x.retVal = 1;
return x;
}
private SubClassA Foo (SubClassA x) {
x.retVal = 2;
return x;
}
[Test]
public void OverloadTest(){
TopClass t = new TopClass();
TopClass t1 = new SubClassA();
SubClassA s1 = new SubClassA();
t = Foo (t);
t1 = Foo (t1);
s1 = Foo (s1);
Assert.AreEqual(1, t.retVal);
Assert.AreEqual(2, s1.retVal);
Assert.AreEqual(2, t1.retVal);
}
}
So my question boils down to: "How can the test above be fixed in an elegant, polymorphic, object-oriented way without resorting to is-checks?"
Extension Methods
I have also tried using extension methods as follows. This did not solve the problem, since they are merely syntactical sugar for the approach above:
using NUnit.Framework;
using ExtensionMethods;
public class TopClass{
public int retVal;
}
public class SubClassA : TopClass{ }
[TestFixture]
public class ThrowawayTest {
private TopClass Foo (TopClass x) {
x.retVal = 1;
return x;
}
private SubClassA Foo (SubClassA x) {
x.retVal = 2;
return x;
}
[Test]
public void OverloadTest(){
TopClass t = new TopClass();
TopClass t1 = new SubClassA();
SubClassA s1 = new SubClassA();
t.Foo(); s1.Foo(); t1.Foo();
Assert.AreEqual(1, t.retVal);
Assert.AreEqual(2, s1.retVal);
Assert.AreEqual(2, t1.retVal);
}
}
namespace ExtensionMethods{
public static class Extensions {
public static void Foo (this TopClass x) {
x.retVal = 1;
}
public static void Foo (this SubClassA x) {
x.retVal = 2;
}
}
}
Similarly to Kevin's answer, I'd consider taking advantage of the dynamic keyword. I'll just mention two additional approaches.
Now, you don't really need access to the source code, you just need access to the types themselves, meaning, the assembly. As long as the types are public (not private or internal) these should work:
Dynamic Visitor
This one uses a similar approach to the conventional Visitor pattern.
Create a visitor object, with one method for each sub-type (the end types, not intermediate or base classes such as Command), receiving the external object as parameter.
Then to invoke it, on a specific object of which you don't know the exact type at compile-time, just execute the visitor like this:
visitor.Visit((dynamic)target);
You can also handle recursion within the visitor itself, for types that have sub-expressions you want to visit.
Dictionary of Handlers
Now, if you only want to handle a few of the types, not all of them, it may be simpler for you to just create a Dictionary of handlers, indexed by Type. That way you could check if the dictionary has a handler for the exact type, if it does, invoke it. Either through standard invocation which may force you to cast within your handler, or through a DLR invocation, which won't but will have a bit of a performance hit).
I'm not sure if it's supported in Mono, but you can accomplish what you're looking for by a very specific use of generics & the dynamic keyword in C# 4.0. What you're attempting to do is create a new virtual slot, but with slightly different semantics (C# virtual functions aren't covariant). What dynamic does is push function overload resolution to runtime, just like a virtual function (though much less efficiently). Extension methods & static functions both have compile-time overload resolution, so the static type of the variable is what's used, which is the problem you're fighting.
public class FooBase
{
public int RetVal { get; set; }
}
public class Bar : FooBase {}
Setting up a dynamic visitor.
public class RetValDynamicVisitor
{
public const int FooVal = 1;
public const int BarVal = 2;
public T Visit<T>(T inputObj) where T : class
{
// Force dynamic type of inputObj
dynamic #dynamic = inputObj;
// SetRetVal is now bound at runtime, not at compile time
return SetRetVal(#dynamic);
}
private FooBase SetRetVal(FooBase fooBase)
{
fooBase.RetVal = FooVal;
return fooBase;
}
private Bar SetRetVal(Bar bar)
{
bar.RetVal = BarVal;
return bar;
}
}
Of particular interest are the types of inputObj, #dynamic in Visit<T> for Visit(new Bar()).
public class RetValDynamicVisitorTests
{
private readonly RetValDynamicVisitor _sut = new RetValDynamicVisitor();
[Fact]
public void VisitTest()
{
FooBase fooBase = _sut.Visit(new FooBase());
FooBase barAsFooBase = _sut.Visit(new Bar() as FooBase);
Bar bar = _sut.Visit(new Bar());
Assert.Equal(RetValDynamicVisitor.FooVal, fooBase.RetVal);
Assert.Equal(RetValDynamicVisitor.BarVal, barAsFooBase.RetVal);
Assert.Equal(RetValDynamicVisitor.BarVal, bar.RetVal);
}
}
I hope that's feasible in Mono!
Here is version without dynamic, dynamic version is too slow (first call):
public static class Visitor
{
/// <summary>
/// Create <see cref="IActionVisitor{TBase}"/>.
/// </summary>
/// <typeparam name="TBase">Base type.</typeparam>
/// <returns>New instance of <see cref="IActionVisitor{TBase}"/>.</returns>
public static IActionVisitor<TBase> For<TBase>()
where TBase : class
{
return new ActionVisitor<TBase>();
}
private sealed class ActionVisitor<TBase> : IActionVisitor<TBase>
where TBase : class
{
private readonly Dictionary<Type, Action<TBase>> _repository =
new Dictionary<Type, Action<TBase>>();
public void Register<T>(Action<T> action)
where T : TBase
{
_repository[typeof(T)] = x => action((T)x);
}
public void Visit<T>(T value)
where T : TBase
{
Action<TBase> action = _repository[value.GetType()];
action(value);
}
}
}
Interface declaration:
public interface IActionVisitor<in TBase>
where TBase : class
{
void Register<T>(Action<T> action)
where T : TBase;
void Visit<T>(T value)
where T : TBase;
}
Usage:
IActionVisitor<Letter> visitor = Visitor.For<Letter>();
visitor.Register<A>(x => Console.WriteLine(x.GetType().Name));
visitor.Register<B>(x => Console.WriteLine(x.GetType().Name));
Letter a = new A();
Letter b = new B();
visitor.Visit(a);
visitor.Visit(b);
Console output : A, B, take a look for more details.
The documentation on static constructors in C# says:
A static constructor is used to
initialize any static data, or to
perform a particular action that needs
performed once only. It is called
automatically before the first
instance is created or any static
members are referenced.
That last part (about when it is automatically called) threw me for a loop; until reading that part I thought that by simply accessing a class in any way, I could be sure that its base class's static constructor had been called. Testing and examining the documentation have revealed that this is not the case; it seems that the static constructor for a base class is not guaranteed to run until a member of that base class specifically is accessed.
Now, I guess in most cases when you're dealing with a derived class, you would construct an instance and this would constitute an instance of the base class being created, thus the static constructor would be called. But if I'm only dealing with static members of the derived class, what then?
To make this a bit more concrete, I thought that the code below would work:
abstract class TypeBase
{
static TypeBase()
{
Type<int>.Name = "int";
Type<long>.Name = "long";
Type<double>.Name = "double";
}
}
class Type<T> : TypeBase
{
public static string Name { get; internal set; }
}
class Program
{
Console.WriteLine(Type<int>.Name);
}
I assumed that accessing the Type<T> class would automatically invoke the static constructor for TypeBase; but this appears not to be the case. Type<int>.Name is null, and the code above outputs the empty string.
Aside from creating some dummy member (like a static Initialize() method that does nothing), is there a better way to ensure that a base type's static constructor will be called before any of its derived types is used?
If not, then... dummy member it is!
You may call static constructor explicity, so you will not have to create any methods for initialization:
System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof (TypeBase).TypeHandle);
You may call it in static constructor of derived class.
As others have noted, your analysis is correct. The spec is implemented quite literally here; since no member of the base class has been invoked and no instance has been created, the static constructor of the base class is not called. I can see how that might be surprising, but it is a strict and correct implementation of the spec.
I don't have any advice for you other than "if it hurts when you do that, don't do that." I just wanted to point out that the opposite case can also bite you:
class Program
{
static void Main(string[] args)
{
D.M();
}
}
class B
{
static B() { Console.WriteLine("B"); }
public static void M() {}
}
class D: B
{
static D() { Console.WriteLine("D"); }
}
This prints "B" despite the fact that "a member of D" has been invoked. M is a member of D solely by inheritance; the CLR has no way of distinguishing whether B.M was invoked "through D" or "through B".
The rules here are very complex, and between CLR 2.0 and CLR 4.0 they actually changed in subtle and interesting ways, that IMO make most "clever" approaches brittle between CLR versions. An Initialize() method also might not do the job in CLR 4.0 if it doesn't touch the fields.
I would look for an alternative design, or perhaps use regular lazy initialization in your type (i.e. check a bit or a reference (against null) to see if it has been done).
In all of my testing, I was only able to get a call to a dummy member on the base to cause the base to call its static constructor as illustrated:
class Base
{
static Base()
{
Console.WriteLine("Base static constructor called.");
}
internal static void Initialize() { }
}
class Derived : Base
{
static Derived()
{
Initialize(); //Removing this will cause the Base static constructor not to be executed.
Console.WriteLine("Derived static constructor called.");
}
public static void DoStaticStuff()
{
Console.WriteLine("Doing static stuff.");
}
}
class Program
{
static void Main(string[] args)
{
Derived.DoStaticStuff();
}
}
The other option was including a static read-only member in the derived typed that did the following:
private static readonly Base myBase = new Base();
This however feels like a hack (although so does the dummy member) just to get the base static constructor to be called.
I almost alway regret relying on something like this. Static methods and classes can limit you later on. If you wanted to code some special behavior for your Type class later you would be boxed in.
So here is a slight variation on your approach. It is a bit more code but it will allow you to have a custom Type defined later that lets you do custom things.
abstract class TypeBase
{
private static bool _initialized;
protected static void Initialize()
{
if (!_initialized)
{
Type<int>.Instance = new Type<int> {Name = "int"};
Type<long>.Instance = new Type<long> {Name = "long"};
Type<double>.Instance = new Type<double> {Name = "double"};
_initialized = true;
}
}
}
class Type<T> : TypeBase
{
private static Type<T> _instance;
public static Type<T> Instance
{
get
{
Initialize();
return _instance;
}
internal set { _instance = value; }
}
public string Name { get; internal set; }
}
Then later when you get to adding a virtual method to Type and want a special implementation for Type you can implement thus:
class TypeInt : Type<int>
{
public override string Foo()
{
return "Int Fooooo";
}
}
And then hook it up by changing
protected static void Initialize()
{
if (!_initialized)
{
Type<int>.Instance = new TypeInt {Name = "int"};
Type<long>.Instance = new Type<long> {Name = "long"};
Type<double>.Instance = new Type<double> {Name = "double"};
_initialized = true;
}
}
My advice would be to avoid static constructors - it is easy to do. Also avoid static classes and where possible static members. I am not saying never, just sparingly. Prefer a singleton of a class to a static.
Just an idea, you can do something like this:
abstract class TypeBase
{
static TypeBase()
{
Type<int>.Name = "int";
Type<long>.Name = "long";
Type<double>.Name = "double";
}
}
class Type<T> : TypeBase
{
static Type()
{
new Type<object>();
}
public static string Name { get; internal set; }
}
class Program
{
Console.WriteLine(Type<int>.Name);
}