Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reference the "self" type in a static method - C#

Tags:

c#

I am trying to create a static method that would return an instance of the class, something like:

class A {
   public static A getInstance() {
      return new A();
   }
}

The problem I am having is that if I have a subclass B derived from A, I would like B.getInstance() to return an instance of B, and not A. In PHP world, you could use a keyword "self" to reference to your own type, so your getInstance() would look like:

public static function getInstance() {
   return new self();
}

What's the best way to go about this?

like image 664
m1tk4 Avatar asked Aug 23 '11 14:08

m1tk4


People also ask

How do I call a static method from another class in C++?

By declaring a function member as static, you make it independent of any particular object of the class. A static member function can be called even if no objects of the class exist and the static functions are accessed using only the class name and the scope resolution operator ::.

Can we call static member function of a class using object of a class in C++?

You cannot have static and nonstatic member functions with the same names and the same number and type of arguments. Like static data members, you may access a static member function f() of a class A without using an object of class A .

What is static class in c3?

A static class can only contain static data members, static methods, and a static constructor.It is not allowed to create objects of the static class. Static classes are sealed, means you cannot inherit a static class from another class. Syntax: static class Class_Name { // static data members // static method }

What is the difference between using self and this PHP?

The keyword self is used to refer to the current class itself within the scope of that class only whereas, $this is used to refer to the member variables and function for a particular instance of a class.


2 Answers

You can't, basically. If a call to a static member which is only declared in a base class is actually expressed in terms of the derived class, like this:

// Urgh
Encoding ascii = ASCIIEncoding.ASCII;

// Worse yet (and yes, I've seen this)
Encoding ascii = UTF8Encoding.ASCII;

then the compiler silently transforms that to:

Encoding ascii = Encoding.ASCII;

The fact that the original source contained the name of a derived class is not preserved in the compiled code, so it can't be acted on at execution time.

like image 156
Jon Skeet Avatar answered Oct 24 '22 03:10

Jon Skeet


How about using generics to provide the type to produce:

public static T getInstance<T>() where T : A, new()
{
    return new T();
}
like image 44
George Duckett Avatar answered Oct 24 '22 02:10

George Duckett