c# language suggestion

  • Thread starter Thread starter zeromus
  • Start date Start date
Z

zeromus

I wish c# could define some keyword as a modifier on a variable declaration,
and what it would do is automatically assign the variable to an instance
created by the default constructor
I have not thought carefully about the syntax, but some examples are called
for:


default MyClass myvar1, myvar2, myvar3;
---->
MyClass myvar1 = new Myclass();
MyClass myvar2 = new Myclass();
MyClass myvar3 = new Myclass();

and especially:

default MyClass[100] myarr;
---->
MyClass[] myarr = new MyClass[];
for(int i=0;i<100;i++)
myarr = new MyClass();

and in the case of arrays it is irritating to have the initialization
sometimes needing to be done far away from the declaration...

or is there some way to do something like this that I just do not know
about?

Forgive me if this has already been thought of before. But I am tired of
typing so much extra!
 
If you need this functionality often, you can create a helper class to do
the work for you. Here's an example that will automatically allocate the
array and initialize the elements by calling the parameterless constructor
multiple times.

public class MyClass
{
public MyClass()
{
System.Diagnostics.Trace.WriteLine("MyClass constructor
called");
}
}

public class ClassInitializer
{
public static void FillArray(Array array)
{
Type type = array.GetType().GetElementType();
System.Reflection.ConstructorInfo constructor =
type.GetConstructor(Type.EmptyTypes);
for (int i=0; i<array.Length; i++)
array.SetValue(constructor.Invoke(null), i);
}

public static Array CreateArray(Type elementType, int length)
{
Array array = Array.CreateInstance(elementType, length);
FillArray(array);
return array;
}
}

class TestApp
{
[STAThread]
static void Main(string[] args)
{
MyClass[] arr = (MyClass[])
ClassInitializer.CreateArray(typeof(MyClass), 100);
}
}
 
Back
Top