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.
Related
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.
Problem Description
I'm trying to implement a very specific sort of cache of objects that I may not be able to instantiate directly (private constructors for instance)
What I want to do is read some information about the particular class, preferably through some kind of interface (which sadly doesn't support static methods defined for every subclass)
In other words:
public class Data
{
public static bool Attribute1() => False;
private Data(...) { ... }
}
public class Cache<T> // T is for instance Data
{
void SomeMethod()
{
bool Value = T.Attribute1()
...
}
}
It's fine if I can make T inherit from some base class or some interface, and to get the attribute through some sort of method or directly. It is very important though that I can
Program multiple data classes A and B, where A.Attribute1() is different from B.Attribute1()
Get the attribute from the data class type without instantiating the data type
Current Solution
I do currently have a solution in the shape of a registry built when the static objects are initialised, like this:
class CacheAttributesRegistry
{
static RegisterAttributes(Type T, bool Attribute1, ...) { ... }
}
class Data
{
static Data() { RegisterAttributes(typeof(Data), true, ...); }
}
class Cache<T>
{
void SomeMethod()
{
bool Value = CacheAttributesRegistry.Attribute1(typeof(T));
}
}
It does exactly what I want, but I'd prefer avoiding a static constructor in every data class, also I don't want it to be possible to accidentally call RegisterAttributes at runtime.
Preferably I'd also avoid reflection because I'd like it to be obvious how to set the attributes for a class without the code magically inferring it in the background.
Am I missing some option or have I just reached some language limitations?
We have a Static field in a abstract class
ABSTRACT CLASS :-
public abstract class BaseController
{
private static string a;
private static string b;
protected abstract SomeArray[] DoSomeThing();
}
And a derived class
public class Controller1:BaseController
{
protected override SomeArray[] DoSomthing()
{
//////
In this method we are setting the static variables with different values
}
}
We also have a class which is starting threads
public class SomeClass
{
public SomeClass()
{
\\ we are setting the controller we want to call, i mean to decide which base class to call
}
public void Run()
{
Thread t = new Thread(StartThread);
t.Start();
}
public void StartThread()
{
_controller.DoSomeThing();
}
}
All the above service is in a WCF service, and the same client tries to call multiple times which means we have multiple threads running at the same time, we have seen issues where the static variable which we are setting and using that for some DB update process is sometimes having wrong values
I have read some blogs which says static fields are not thread safe, Can some body please help me understand what could be going wrrong in our code and why we are having some incorrect values passed to the DB.
By definition, a static field or member is shared among all instances of that class, only one instance of that field or member exisits; thus, it is not thread safe.
You have two options, either to synchronize the access (basically, using Monitor class) to that field or to use the ThreadStaticAttribute on that field.
However, i advice to reorganize your class hierarchy so that each class has its own instance of the field or member.
Please note that if there are multiple threads working on the same instance of the class Controller, then we go back to the same problem and you should synchronize access to that instance field.
Good Luck
I have a job interview tomorrow and I'm trying to answer this question:
There is a class named C and method m in this class, this class have also empty constructor:
Main ()
{
C c = new c();
}
Class C {
public c {
//empty constructor
}
public m {
//does something - doesnt mind
}
}
And what you have to do is to change the code so that in a creation of an instance class C, the method m would be called before the class constructor.
You have to do this without changing the main (edit only the class code).
Thanks in advance!
Like the other answers have said, you can make the method static. But then you need to explicitly call it. If you make a static class constructor, that will get called once automatically (you don't need to call it), the first time the class is referenced (like when you construct the first instance). You can't exactly control when it executes, but it will execute before the first instance is constructed. Based on the way they've worded the question (you can't change the Main method), I think static class constructor is the answer they're looking for.
http://msdn.microsoft.com/en-us/library/k9x6w0hc%28v=vs.80%29.aspx
Static constructors have the following properties:
A static constructor does not take access modifiers or have parameters.
A static constructor is called automatically to initialize the class before the first instance is created or any static members are
referenced.
A static constructor cannot be called directly.
The user has no control on when the static constructor is executed in the program.
Java doesn't have static class constructors, but they do have static initialization blocks..
static {
// code in here
}
To call a class's method before its constructor gets called you either have to turn this method into static so you don't need an instance of that class to call it, or (in C#) you can use FormatterServices.GetUninitializedObject Method to get an instance of your class without running the constructor (which of course may not be a wise thing to do).
In JAVA:
make method static and call your method in static block.
class C{
static{
m();
}
public C() {
System.out.println("Constructor Called..");
}
public static void m() {
System.out.println("m() is called.");
}
}
Main call
public static void main(String[] args) {
new C();
}
In both Java and C# you can use, base class constructors, static constructors (Edit: static initializer block in Java), and field initializers, to call code before the C class's constructor executes without modifying Main.
An example using a field initializer block in Java:
class C {
{ m(); }
public C() {
System.out.println("cons");
}
public void m() {
System.out.println("m");
}
}
This prints "m", then "cons". Note that m is called every time a C is constructed. A static initializer block would only be called once for the JVM.
Its basic OOP. You have to make a public static method and call it. That method can then call the constructor, or you can call the constructor directly from main.
Before you call the constructor, the object don't exist, therefore no instance methods exist, therefore nothing tied to the instance/object can be called. The only things that do exist before the constructor is called is the static methods.
Following way seems to achieve what is required. Without using static methods/variables
namespace FnCallBeforeConstructor
{
static void Main(string[] args)
{
MyClass s = new MyClass();
Console.ReadKey();
}
partial class MyClass: Master
{
public override void Func()
{
Console.WriteLine("I am a function");
}
public MyClass()
: base()
{
Console.WriteLine("I am a constructor");
}
}
class Master
{
public virtual void Func() { Console.WriteLine("Not called"); }
public Master()
{
Func();
}
}
}
Output is:
I am a function
I am a constructor
What is the need of private constructor in C#?
I got it as a question for a C# test.
For example if you have a class that should only be created through factory methods. Or if you have overloads of the constructor, and some of them should only be used by the other constructors. Probably other reasons as well =)
If you know some design pattern, it's obvious: a class could create a new instance of itself internally, and not let others do it.
An example in Java (I don't know C# well enough, sorry) with a singleton-class:
class Meh
{
private Meh() { }
private static Meh theMeh = new Meh();
public static Meh getInstance() { return theMeh; }
}
Whenever you want to prevent direct instantiation of a class from outside of it, you'll use a private constructor. For example, prior to C# 2.0 which introduced static classes, you used a private constructor to accomplish roughly the same thing:
sealed class StaticClass {
private StaticClass() {
}
public static void DoSomething() {
}
}
When you want to prevent the users of your class from instantiating the class directly. Some common cases are:
Classes containing only static methods
Singletons
I can can recall few usages for it:
You could use it from a static factory method inside the same class
You could do some common work inside it and then call it from other contructure
You could use it to prevent the runtime from adding an empty contructure automatically
It could be used (although private) from some mocking and ORM tools (like nhibernate)
For example when you provide factory methods to control instantiation...
public class Test(){
private Test(){
}
void DoSomething(){
// instance method
}
public static Test CreateCoolTest(){
return new Test();
}
}
Private constructors are used to prevent the creation of instances of a class when there are no instance fields or methods, such as the Math class, or when a method is called to obtain an instance of a class. If all the methods in the class are static, consider making the entire class static. For more information see Static Classes and Static Class Members.
class NLog
{
// Private Constructor:
private NLog() { }
public static double e = System.Math.E; //2.71828...
}
The following is an example of a class using a private constructor.
public class Counter
{
private Counter() { }
public static int currentCount;
public static int IncrementCount()
{
return ++currentCount;
}
}
class TestCounter
{
static void Main()
{
// If you uncomment the following statement, it will generate
// an error because the constructor is inaccessible:
// Counter aCounter = new Counter(); // Error
Counter.currentCount = 100;
Counter.IncrementCount();
System.Console.WriteLine("New count: {0}", Counter.currentCount);
}
}
While this link is related to java, I think it should help you understand the reason why as the idea is pretty much the same.
Private constructors prevent a class from being explicitly instantiated by callers. There are some common cases where a private constructor can be useful:
classes containing only static utility methods
classes containing only constants
type safe enumerations
singletons
You can use it with inheritance in a case where the arguments to the constructor for the base class are of different types to those of the child classes constructor but you still need the functionality of the base class in the child class eg. protected methods.
Generally though this should be avoided wherever possible as this is a bad form of inheritance to be using.
I'm late to the game, but reading through all the other answers, I don't see this usage mentioned:
I use private constructors in scenarios where I have multiple (public) constructors, and they all have some code in common. With constructor chaining, the code becomes really neat and DRY.
Remember, the private readonly variables can only be set in constructors, so I can't use a regular method.
Example:
public class MyClass
{
private readonly int _a;
private readonly int _b;
private readonly string _x;
public MyClass(int a, int b, string x)
: this(x)
{
_a = a;
_b = b;
}
public MyClass()
: this("(not set)")
{
// Nothing set here...
}
private MyClass(string x)
{
_x = x;
}
}
Basically you use private constructors when you are following a singleton design pattern. In this case, you have a static method defined inside the class that internally calls the private constructor.
So to create the instance of the class for the first time, the user calls the classname.static_method_name. In this method, since the class's object doesn't yet exist, the static method internally calls the private constructor and returns the class's instance.
If the class's instance already exists, then the static method simply returns the instance to the calling method.
And of course you can use private constructor to prevent subclassing.