OOP - how to call a function before the class constructor - c#

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

Related

Differents in static methods and non static methods in classes without fields

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.

Error - the program is not giving output while calling the print method

This is a simple program I created - one table class, one main class. In the table class I created a print method which simply outputs my name. From the main class I am calling the print method but not getting the output.
namespace ConsoleApplication3
{
class table
{
public static void print()
{
Console.WriteLine("My name is prithvi-raj chouhan");
}
}
class Program
{
public static void Main()
{
table t = new table();
t.print(); // Error the program is not giving output while calling the print method
}
}
}
Since the function you are calling is static.
Use this syntax
public static void Main()
{
table.print();
}
Quote from MSDN:-
A static method, field, property, or event is callable on a class even
when no instance of the class has been created. If any instances of
the class are created, they cannot be used to access the static
member. Only one copy of static fields and events exists, and static
methods and properties can only access static fields and static
events. Static members are often used to represent data or
calculations that do not change in response to object state; for
instance, a math library might contain static methods for calculating
sine and cosine.
print is a static method, so call it as a static method:
public static void Main()
{
table.print();
}
try this:
class Program
{
public static void Main()
{
table.Print();
}
}
Print(); is a static method so you dont need to instantiate a new Table object in order to access it's methods
You are calling print() as an instance method but it is static. Try to remove the static keyword from the method.
Try to add a Console.ReadLine(); after table.print();.
UPDATE:
Missed the part with static, now corrected.

Static constructor called after instance constructor?

Dear all, the question like this one has been already asked, but among the answers there was no explanation of the problem which I see.
The problem: the C# Programming Guide 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.
In particular, static constructor is called before any instance of a class is created. (This doesn't ensure that the static constructor finishes before creation of instance, but this is a different story.)
Let's consider the example code:
using System;
public class Test
{
static public Test test = new Test();
static Test()
{
Console.WriteLine("static Test()");
}
public Test()
{
Console.WriteLine("new Test()");
}
}
public class Program
{
public static void Main()
{
Console.WriteLine("Main() started");
Console.WriteLine("Test.test = " + Test.test);
Console.WriteLine("Main() finished");
}
}
It outputs:
Main() started
new Test()
static Test()
Test.test = Test
Main() finished
So we can see that the instance constructor finishes (and thus an instance is created) before the static constructor starts. Doesn't this contradict the Guide? Maybe the initialization of static fields is considered to be an implicit part of static constructor?
Inline initializers for static fields run before the explicit static constructor.
The compiler transforms your class into something like this:
public class Test {
.cctor { //Class constructor
Test.test = new Test(); //Inline field initializer
Console.WriteLine("static Test()"); //Explicit static ctor
}
.ctor { ... } //Instance constructor
}
Note that this is independent of the declaration order.
To quote the spec:
The static field variable initializers
of a class correspond to a sequence of
assignments that are executed in the
textual order in which they appear in
the class declaration. If a static
constructor (Section 10.11) exists in
the class, execution of the static
field initializers occurs immediately
prior to executing that static
constructor.

Triggering a non-static class from a static class?

I am writing a class library(API) in C#. The class is non-static and contains several public events. Is it possible to trigger those events from a static method in a separate class?
For example...
class nonStaticDLLCLASS
{
public event Event1;
public CallStaticMethod()
{
StaticTestClass.GoStaticMethod();
}
}
class StaticTestClass
{
public static GoStaticMethod()
{
// Here I want to fire Event1 in the nonStaticDLLCLASS
// I know the following line is not correct but can I do something like that?
(nonStaticDLLCLASS)StaticTestClass.ObjectThatCalledMe.Event1();
}
}
I know you typically have to create an instance of the non-static class in order to access it's methods but in this case an instance has already been created, just not by the class that is trying to access it.
No, instance members can only be invoked/accessed on a valid instance of the type.
In order for this to work you must pass an instance of nonStaticDLLCLASS to StaticTestClass.GoStaticMethod and use that instance reference to invoke/access the non-static members.
In your example above how do you specify which instance of the type you are accessing? The static method has no knowdlege of any instance so how does it know which one to use or if there are any loaded in memory at all?
Consider this example:
using System;
class Dog
{
public String Name { get; set; }
}
class Example
{
static void Main()
{
Dog rex = new Dog { Name="Rex" };
Dog fluffy = new Dog { Name="Fluffy" };
}
static void sayHiToDog()
{
// In this static method how can I specify which dog instance
// I mean to access without a valid instance? It is impossible since
// the static method knows nothing about the instances that have been
// created in the static method above.
}
static void sayHiToDog(Dog dog)
{
// Now this method would work since I now have an instance of the
// Dog type that I can say hi to.
Console.WriteLine("Hello, " + dog.Name);
}
}
Instance methods can only be called on instances. In your example, the instance is calling the static method. Can you give the static method a parameter allowing the instance to pass in a reference to itself? Something like this:
class nonStaticDLLCLASS
{
public event Event1;
public CallStaticMethod()
{
StaticTestClass.GoStaticMethod(this);
}
}
class StaticTestClass
{
public static GoStaticMethod(nonStaticDLLCLASS instance)
{
// Here I want to fire Event1 in the nonStaticDLLCLASS
// I know the following line is not correct but can I do something like that?
instance.Event1();
}
}
I think you need to clarify your question to specify why you can't do something like this, or why the instance can't raise its own event.

What is the need of private constructor in C#?

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.

Categories