I have such class in c#:
public class Foo
{
public static readonly int SIZE = 2;
private int[] array;
public Foo
{
array = new int[SIZE];
}
}
and Bar class:
public class Bar : Foo
{
public static readonly int SIZE = 4;
}
What I want to accopmlish is to create a Bar instance with array size taken from overrided SIZE value. How to do it properly?
You can't do it this way. You could use a virtual method:
public class Foo
{
protected virtual int GetSize(){return 2;};
private int[] array;
public Foo
{
array = new int[GetSize()];
}
}
It's also possible to use reflection to look for a static field SIZE, but I don't recommend that.
Your SIZE constant is static, and static fields aren't inherited - Foo.SIZE and Bar.SIZE are two different constants that have nothing to do with each other. That's why Foo's constructor call will always initialize with 2, not 4.
What you can do is create a protected virtual void Initialize() method in Foo that initializes the array with 2, and override it in Bar to initialize it with 4.
You cannot inherit static fields; instead use the below:
public class Foo
{
protected virtual int SIZE
{
get
{
return 2;
}
}
private int[] array;
public Foo()
{
array = new int[SIZE];
}
}
public class Bar : Foo
{
protected override int SIZE
{
get
{
return 4;
}
}
}
Virtual is like saying "This is the default value of the base class"; whilst Override changes the value on the class implementing "Foo".
Related
I'm trying to modify a bunch of static value variables as fields in a static class. They need to be initialized in some sort of structure with a string attached to them, but the outside world should be able to just get the variable directly.
Here's a basic code dump of what I'm trying to do (disregard the specifics inside of DoStuff(); just an example of the kind of operations I'm trying to do):
public unsafe static class StaticVariables
{
public static int foo;
public static int bar;
...
public static int bazinga;
static IEnumerable<StaticInteger> intList = new List<StaticInteger>
{
new StaticInteger(&foo,"foo"),
new StaticInteger(&bar,"bar"),
...
new StaticInteger(&bazinga,"bazinga")
};
public static void DoStuff()
{
foreach(StaticInteger integer in intList)
{
if(integer.identifier=="foo") *integer.pValue = 30;
if (integer.identifier == "bar") *integer.pValue = 23;
}
Console.WriteLine("{0} {1}", foo, bar);
}
}
public unsafe class StaticInteger
{
public int* pValue;
public string identifier;
public StaticInteger(int* pValue, string identifier)
{
this.pValue = pValue;
this.identifier = identifier;
}
}
I'm not able to grab the address of foo/bar where I want to. They're static/globals, so they shouldn't going anywhere. I can cheat and use fixed inside of DoStuff to initialize the list, but I want to be able to reference my list multiple times after initialization, and I'm not sure that's safe because we'd no longer be in the fixed block. Is there a way to tell the GC "Don't touch where you put this static variable please"?
I'd be super happy if the answer was "don't use pointers, do XYZ instead."
Using a properties with only a getter rather than fields you can limit users to only reading values & the values can be stored in a Dictionary rather than a list.
public static class StaticVariables
{
public static int foo { get {return values["foo"];}}
public static int bar { get {return values["bar"];}}
public static int bazinga { get {return values["bazinga"];}}
private static Dictionary<String,int> values = new Dictionary<String,int>();
static StaticVariables()
{
values.Add("foo",0);
values.Add("bar",0);
values.Add("bazinga",0);
}
public static void DoStuff()
{
values["foo"] =30;
values["bar"] =23;
}
}
I cant access static method from new object and not allow create same name non-static method.I need to use same name method static and non-static.
Foo class has some default variables. I create new object and set default variables.
Sample code block
class Foo
{
public void abc()
{
//...
}
public static string xyz(string s)
{
return "bla bla";
}
}
public void btn1_click()
{
System.Windows.Forms.MessageBox.Show(Foo.xyz("value"));
//Works OK
}
public void btn1_click()
{
Foo f1=new Foo();
//f1..
f1.xyz("value");
//Cant access non static method.
}
Thanks in advance.
If the class has default values, the correct place to populate them is in the class constructor:
public class Foo
{
public Foo()
{
// set default values here.
}
}
If you still want to use these default values as static members - no problem:
public class Foo
{
public static const int DEFAULT_INT_VALUE = 5;
public Foo()
{
IntValue = DEFAULT_INT_VALUE;
}
public int IntValue {get;set;}
}
I have a base class with a protected-level static variable, a protected-level static function, and a public function:
public class ClassA
{
protected static int Size = 4;
public static byte[] DoSomething(byte[] params)
{
// use Size somehow
params = DoSomethingElse(params);
return params;
}
protected static byte[] DoSomethingElse(byte[] params)
{
// do whatever
return params;
}
}
And a derived class that hides the protected-level variable and function:
public class ClassB : ClassA
{
public new static int Size = 2;
protected new static byte[] DoSomethingElse(byte[] params)
{
// do something different than base class
return params;
}
}
Now, when I call ClassB.DoSomething, I want the Size value and DoSomethingElse from the ClassBto be used, but the ClassA values are used instead. Is there a way to make this use the ClassB variable and method?
I often find myself doing this:
class MyClass
{
public MyClass(int x)
{
this.x = x;
}
private int x;
...
}
Every time I add a new private member variable for configuration, I need to add it to the constructor's parameter list, to the constructor body, and to the class as a member. Is there a good programming pattern for avoiding the extra typing?
Generally speaking, If you instantiate a class with a bunch of private members that you have to pass into the constructor, you're doing something problematic already.
MyClass myClass = new MyClass(x, y, z, 7, 'c', someOtherClass)
If appropriate, you can encapsulate related fields into a struct or a different class like so
class MyClass
{
public MyClass(Coordinates coords)
{
this.coords = coords;
}
private Coordinates coords;
}
public struct Coordinates
{
public int X{get; set;}
public int Y{get; set;}
public int z{get; set;}
}
and then you can instanciate it with
MyClass myClass = new MyClass(new Coordinates() { X = 1, Y = 2, Z = 3 });
Without a particular implementation, It's kinda hard to determine the optimal solution, but if you don't actually have to set the fields from outside your class, you can do something like
class MyClass
{
public MyClass()
{
}
private int x = 2;
...
}
or
class MyClass
{
public MyClass()
{
this.x = 2;
}
private int x;
...
}
I find that I can abuse inheritance to accomplish my goal. I set up a "Loader" subclass that has the sole purpose in life of plugging in the dependencies of the base class. Then we can work with the base class and forget about the loader.
Then again, this has the horrible side-effect of preventing use of these protected member variables in the base constructor -- we need to use a .Start() function or something like that instead. So, this is a pretty bad solution, although saving some keystrokes.
public class MyClass
{
protected int param1;
protected int param2;
public void DoStuff()
{
Console.WriteLine(param1 + param2);
}
}
public class MyClassLoader : MyClass
{
public MyClassLoader()
{
param1 = 1;
param2 = 2;
}
}
class Program
{
static void Main(string[] args)
{
MyClass myObj = new MyClassLoader();
myObj.DoStuff();
Console.WriteLine("Press any key to quit.");
Console.ReadKey();
}
}
I seem to remember some kind of short hand way to initialize fields of a class sent to a constructor, something like:
Class A {
int n;
public A(int N) : n(N) {}
}
Any clues?
There is easy way to initialize class fields after constructor like this:
public class A
{
public int N;
public string S;
public A() {}
}
class B
{
void foo()
{
A a = new A() { N = 1, S = "string" }
}
}
That would be C++, but you tagged your question C#. C# has no notion of initialization lists, you simply assign your fields in the constructor. You can however chain constructors or call a base class constructor in a similar manner
// call base class constructor before your own executes
public class B : A
{
public B(int whatever)
: base(something)
{
// more code here
}
}
// call secondary constructor
public class B : A
{
private int _something;
public B() : this(10) { }
public B(int whatever)
{
_something = whatever;
}
}