To be more clear about my question, if you create an array of a particular class: for example,
ExampleClass[] test = new ExampleClass[5];
I know the five ExampleClass instances would create a copy of each variable for each class, but are the methods/functions duplicated 5 times in memory, or do each of the tests just point to the same single class codebase? If it duplicated for each class, that would just be a waste of memory.
Every type loaded into an AppDomain will have a Method Table structure that holds every method that type defines, plus the virtual methods derived from parent (typically Object) and the methods defined by any implemented interface.
This Method Table is pointed by every instance of that object. So every instance does not duplicate all the methods defined by that type, but points to this method table structure with a reference.
For example:
public class MyClass : IDisposable
{
private static void MyStaticMethod()
{
// ....
}
public void MyInstanceMethod()
{
// ....
}
public void Dispose()
{
throw new NotImplementedException();
}
}
This MyClass will have a method table including:
MyStaticMethod
MyInstanceMethod
Dispose
And other virtual methods derived from System.Object
Have a look at nice diagram of method table:
You can check the whole article about method tables here
Related
With those classes:
public abstract class T_BaseClass
{
public virtual void m_canvas()
{
Console.WriteLine("canvas method called from template.");
}
}
public class C_ChildT : T_BaseClass
{
public override void m_canvas()
{
base.m_canvas();
Console.WriteLine("canvas method called from child template.");
}
}
What is the differences between those two implementations?
Difference between
C_ChildT mychildclass = new C_ChildT();
and
T_BaseClass mychildclass1 = new C_ChildT();
mychildclass.m_canvas();
mychildclass1.m_canvas();
Hope it looks better M.Skeet.
Thank you for your answer.
Basically, you don't need a deep understanding of inheritance to work with it. The minimum, that you should know is that the last child of inheritance sequence methods is called, when you call any method on an object. Also you should know that variable type and object type are different things, and you can store an object of child types in a variable of parent type. So, in your example you have two variables with C_ChildT and T_BaseClass types. But both objects are C_ChildT type. So when you call m_canvas() on each of them, you will call the C_ChildT implementation of m_canvas() in both cases.
Under the hood, when you call a virtual method, your runtime evironment sees, that the method is marked with the virtual keyword, so it (runtime environment) starts looking for overrriding of this method in the most derived class. You can read more about it here.
Someone once wrote:
The space required for an instance depends only on the fields.
The methods require memory too but only one time per class. Like static fields. That memory is allocated when the class is loaded.
But what happens if a class with say like 5 methods and no fields get multiple instances in fields of other classes(composition).
Do they require more memory? Or would it be the same as static methods?
I do ask this question also because maybe it even gets optimised when compiling?
Is there a differents to static class with static methods? Other than u need to create the class each time or pass it around?
Eg.:
class Test1
{
public void DoThis()
{
...
}
public void DoThat()
{
...
}
}
class Test2
{
public void DoSomething()
{
...
}
private Test1 sample = new Test1();
}
class Test3
{
public void DoSomethingElse()
{
...
}
private Test1 sample = new Test1();
}
And so on...
"Behind the scenes", a class method is just like a static method, with the class instance beeing passes by reference as the first parameter.
That is, unless you use virtual methds, which "behind the scenes" are saved as instance members.
That is, because as long as you don't override a method, there is simply no reason to waste an instance's space.
Therefore, the size of both your class instances won't be affected by any non-virtual method you add to the class.
This concept can change between programming languages tho. For example, in Java and Python class methods are virtual by default.
We all know that we cannot create object of class having private constructor. So the question arises is how many instances of this class can be created .Please find a sample code below.
public class Test
{
public int val ;
private Test(int sent)
{
val=val +sent;
}
public static void Callme(int GetVal)
{
Test obj=new Test(GetVal);
Console.WriteLine(obj.val);
}
}
public class Program
{
public static void Main()
{
Test.Callme(10);
//Console.WriteLine(Test.val);
Test.Callme(20);
//Console.WriteLine(Test.val);
}
}
As per what I know It should create 2 object of the class. Need help understanding this.
We all know that we cannot create object of class having private constructor.
Well, that's not accurate. You can create an object (instance) of a class having only private constructors by using static members of that class, just like in the code in the question.
What you can't do is create an instances of that class from anywhere else in the code.
how many instances of this class can be created
In your code sample there are two instances of class Test.
I think what might be confusing you is you expected the second Console.WriteLine to print 30, but it printed 20. That is because public int val ; is an instance member. If it was a static member, than it would have printed 30
Maybe something like this is what you're looking for:
public static Test Callme(int GetVal)
{
Test obj = new Test(GetVal);
Console.WriteLine(obj.val);
return obj;
}
And then create new instances like:
Test test1 = Test.Callme(10);
Test test2 = Test.Callme(20);
This way you can easily access the members of each instance. E.g. test1.val
Callme method is a static method. Static methods does not require an objects instance to be called upon. They don't have the this (keyword) reference and can be called directly on the class. In your situation Test.CallMe(someValue). Note that there is no object instance involved here.
If CallMe was NOT a static method you would have needed an instance/object to call it. For example
Test ob = new Test();
ob.CallMe(someValue);
What your example illustrates is the use of private fields/methods.
When a method like the constructor or a filed is marked with the private keyword that method/field can only be called/accessed from within the declaring class.
This means that CallMe can access the constructor because CallMe is a member of the class and the constructor is a member of the class thus they both can access each other.
When a class has only one constructor and that constructor is private it effectively means that an instance of the class can only be created from within the class.
So in current example CallMe creates an instance of the class each time it's called.
If you call CallMe 2 times you'll create 2 instances of the class.
Because the method Callme is static it is instantiated by the system at some point before it is used and then remains in memory for future calls. There is only one copy of a static memeber of a class ever created regardless of how many instances of the class are created.
I have a base class DataSet and several derived classes (DataSetSeries, DataSetTable, ...). The constructors of the derived classes each take exactly one argument the type of which is specific to the derived class, e.g.
public DataSetSeries(Series s);
public DataSetTable(Table t);
I have written a (generic) factory class that allows me to create instances of DataSet subclasses from the corresponding original data types, e.g.
DataSet aDataSetSeries = DataSet.Factory.Create(aSeries);
DataSet aDataSetTable = DataSet.Factory.Create(aTable);
where DataSet.Factory is a static readonly field of DataSet. What Create does is determine the type of its argument, then try to lookup the corresponding constructor delegate (which has been registered before) from a dictionary and execute the delegate if it exists.
So I have to register each of the derived classes' constructors at the factory. In order to keep similar things close together and not to forget to add the registration for any new DataSet subclass, I wanted to do this registration in the derived DataSet-classes instead of DataSet itself (which isn't supposed to know any of its derived classes in a strict OO sense). Because Factory is static, I am trying to include a static constructor in each derived DataSet, e.g.
public class DataSetSeries: DataSet
{
static DataSetSeries()
{
Factory.Register(typeof(Series), data => new DataSetSeries((Series)data));
}
// ...
}
But now here is my problem: the static constructor of DataSetSeries will only be called upon first usage of DataSetSeries. But the first thing I will do is call DataSet.Factory.Create(aSeries), which is not a method of DataSetSeries and so there is no first usage of DataSetSeries at all. Hence the static constructor will never be called.
How could I get this working without explicitely iterating over all derived types (which was the reason for setting up the factory in the first place)?
You can create a static constructor for factory and inside this constructor can find all sub-classes of Dataset (DataSetSeries, DataSetTable, ...). and call static constructor for them.
public static class Factory
{
static Factory()
{
var datasetDerrivedTypes = Assembly
.GetExecutingAssembly()
.GetTypes()
.Where(t => typeof(DataSet).IsAssignableFrom(t) &&
t != typeof(DataSet));
foreach (var type in datasetDerrivedTypes)
{
System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(type.TypeHandle);
}
}
public static void Register(Type type, Func<Series, DataSet> constructorDelegate)
{
}
}
How does C#, or other languages for that matter, handle memory allocation (and memory de-allocation) between these two scenarios:
1.) A method on a static class is invoked.
public Program {
Foo foo = Loader.load();
}
public static Loader {
public static Foo load() {
return new Foo();
}
}
2.) A method is invoked on an instance, which then falls out of scope.
public Program {
Foo foo = new Loader().load();
}
public Loader {
public Foo load() {
return new Foo();
}
}
I suppose the static class is loaded, and remains, in memory; whereas the class instance succumbs to garbage collection at C#'s leisure. Are there any pros or cons to these two paradigms? Is there ever a time when you have a class that never needs to be instantiated (i.e. some sort of resource loader or factory), but you use the second methodology anyway to take advantage of garbage collection?
The important part of my question is whether or not the first paradigm, while being conceptually correct in some circumstances, may suffer from holding on to memory unnecessarily.
Your second example doesn't work, so let's explore the real options:
1.) A method on a static class is invoked.
public Program {
Foo foo = Loader.Load();
}
public static Loader {
public static Foo Load() {
return new Foo();
}
}
2.) A static method in a non-static class is invoked.
public Program {
Foo foo = Loader.Load();
}
public Loader {
public static Foo Load() {
return new Foo();
}
}
3.) An instance method is invoked on an instance
public Program {
Foo foo = new Loader().Load();
}
public Loader {
public Foo Load() {
return new Foo();
}
}
The two first are the same. Calling a static method is the same regardless if the class is static or not.
The third option will create an instance of the class on the heap. As the class has no data members, it will only be something like 16 bytes. It will be garbage collected eventually, but due to the small size it doesn't matter much when that happens.
Calling an instance method is also slightly different from a static method. A reference to the class instance is sent along, that you can access through the this keyword. It makes little difference in this case as there is no real data in the object to access.
The second form creates a temporary Loader object (which is very cheap). You will always have to load the Loader class, no matter which approach you choose.
There is very little performance (memory saving) to gain here. You would normally choose for a static member in a static class if there is no 'state' needed outside the methods local vars.
A static method, field, property, or event is callable on a class even when no instance of the class has been created.
http://msdn.microsoft.com/en-us/library/79b3xss3(VS.80).aspx
So in that sense your static methods behaves just as it would if you used it from within a class instance: it is scoped to the type.
I cannot find any sources for this, but from my knowledge of programming, when you refernce a class(non static), it's structure is loaded into memory
Creating an instance of a class just to call a method, would waste a lot of processing power(due to creating an instance, assigning it memory, and the garbage collecting).
Instead of keeping the definition, and then on top of it, an instance. Why not just keep the definition(static).
As long as you don't store any data in static variables, your static method should take up the same amount of memory as your non static method definition. But using a static method, only the method will be kept in memory and be ready to be called whenever you need without creating instances. Where as, if the method is non static, it will need to be instantiated(using up memory and processing power) and the garbage collected(freeing memory and using up cpu) therefore it is definitely better using a static member. Thats what they are there for.