GetType in static method [duplicate] - c#

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
.NET: Determine the type of “this” class in its static method
How can I make GetType() accessible from a static method?
I have this abstract base class
abstract class MyBase
{
public static void MyMethod()
{
var myActualType = GetType(); // this is an instance method
doSomethingWith(myActualType);
}
}
and an implementation of that class. (I could have many implementations.)
class MyImplementation : MyBase
{
// stuff
}
How can I get myActualType to be typeof(MyImplementation)?

The "type" within a static method is always the specific type, since there is no such thing as a virtual static method.
In your case, this means you can just write:
var myActualType = typeof(MyBase);
Since the "type" of MyMethod, being a static, is always a static method of MyBase.

What about this?
abstract class MyBase<T>
{
public static void MyMethod()
{
var myActualType = typeof(T);
doSomethingWith(myActualType);
}
}
class MyImplementation : MyBase<MyImplementation>
{
// stuff
}

This is the pattern i used.
abstract class MyBase
{
public static void MyMethod(Type type)
{
doSomethingWith(type);
}
}

Related

Why does this code not return the class instance from the interface? [duplicate]

This question already has answers here:
Can a C# class call an interface's default interface method from its own implementation?
(3 answers)
Closed 8 months ago.
When this code is run (I'm using .NET 6.0), it recurses infinitely, and never gets to DoSomething() in IInterface, instead of returning the Class instance from the interface.
It seems because of the return type of the method in the class being the same as in the interface, the compiler seems to think the interface's method is being reimplemented in the class, and the method calls itself.
If the method's return type is changed to the concrete class, it works without a problem. Why is it?
using System;
public class Program
{
public static void Main()
{
var obj = new Class();
var ret = obj.DoSomething();
Console.WriteLine("Finished");
}
}
interface IInterface {
IInterface DoSomething() {
return new Class();
}
}
class Class : IInterface {
// Infinite recursion
public IInterface DoSomething() => ((IInterface)this).DoSomething();
// Works
//public Class DoSomething() => (Class)((IInterface)this).DoSomething();
}
If you mark your interface method as sealed it will prevent recursion, but you won't be able to re-implement the method in another class
interface IInterface {
sealed IInterface DoSomething() {
return new Class();
}
}
class Class : IInterface {
public IInterface DoSomething() => ((IInterface)this).DoSomething();
}
Alternatively, you could make the class implementation private, and access it from another method. This will allow you to re-implement the interface in another class.
internal class Class : IInterface
{
private IInterface DoSomething() => ((IInterface)this).DoSomething();
public IInterface DoSomethingPublic() => DoSomething();
}
Unfortunately, there just isn't support for what you want to do currently. There was a section in the original Default Interface Methods proposal about the possibility of using base() to explicitly call an inherited interface, but that was cut.
I admit that I am not very familiar with default interface methods, but I suspect that the default behavior is to override the implementation, and by marking the interface as sealed you prevent this from happening.
If someone has a better explanation, please correct me!
Some reading material:
Default Interface Methods Proposal
A similar question with hacky workarounds
A. Base class
Classic base class implementation:
class BaseClass {
protected void DoSomething() {
Console.WriteLine("Hello from BaseClass!");
}
}
class Class : BaseClass {
public new void DoSomething() // new or virtual + override
{
Console.WriteLine("Hello from Class");
base.DoSomething();
}
}
B. Helper method
static class Helper {
public static void DoSomething() => Console.WriteLine("Do something!");
}
interface IInterface {
void DoSomething() => Helper.DoSomething();
}
class Class : IInterface {
public void DoSomething() { Console.WriteLine("Hello from Class"); Helper.DoSomething();}
}
C. Static interface method
I would say that this seems to be a case for a base class not an interface, but one way to 'reuse' the interface method is to make the interface method static.
For example:
var obj = new Class();
obj.DoSomething();
Console.WriteLine("Finished");
interface IInterface {
static void DoSomething() {
Console.WriteLine("Hello from IInterface!");
}
}
class Class : IInterface {
public void DoSomething() { Console.WriteLine("Hello from Class"); IInterface.DoSomething();}
}
This prints:
Hello from Class
Hello from IInterface!
Finished

C#: How do I call non-generic static method in generic class without specifying generic type? [duplicate]

This question already has answers here:
Using static method from generic class
(4 answers)
Closed 2 years ago.
So I have, let's say, some class that requires generic type as a parameter:
public class SomeClass<GType> { }
And there I have a static method that doesn't interact with this generic type in any way:
public static void Method() { }
The problem is, when I try to call this method, it requires me to specify this generic type. I could, in fact, put there any type and that would work, but it just doesn't seem quite right, does it?
public class SomeClass
{
public static void DoSomething()
{
}
}
public class SomeClass<GType> : SomeClass
{
public void DoAnotherThing<GType>()
{
}
}
public static void Main(string[] args)
{
SomeClass.DoSomething();
}

Why call object class parameter method linseed of fixed data type parameter in inheritance [duplicate]

This question already has answers here:
Overload resolution and virtual methods
(5 answers)
Closed 5 years ago.
Case 1:
public class BaseClass
{
public virtual void Print(int i)
{
Console.WriteLine("BaseClass Print(int)");
}
}
public class DerivedClass : BaseClass
{
public override void Print(int i)
{
Console.WriteLine("DerivedClass Print(int)");
}
public void Print(object obj)
{
Console.WriteLine("DerivedClass Print(object)");
}
}
static void Main(string[] args)
{
DerivedClass objDerivedClass = new DerivedClass();
int i = 10;
objDerivedClass.Print(i);
}
Output is DerivedClass Print(object).
Case 2:
public class SomeClass
{
public void Print(int i)
{
Console.WriteLine("DerivedClass Print(int)");
}
public void Print(object obj)
{
Console.WriteLine("DerivedClass Print(object)");
}
}
static void Main(string[] args)
{
SomeClass objSomeClass = new SomeClass();
int i = 10;
objSomeClass.Print(i);
}
Output is DerivedClass Print(int).
After calling objDerivedClass.Print(i); method, the output is DerivedClass Print(object). I don't understand why the method Print(object obj) is being called instead of Print(int i).
If DerivedClass does not inherit BaseClass class then output is DerivedClass Print(int).
Please explain.......
This is how overload resolution works with inheritance:
The function that includes the override modifier is excluded from the set of candidates.
Since the function with the object parameter can be used, then the function that is declared in the base is removed from the set of candidates.
The winner is the function with the object parameter.
According to Eric Lippert (from Microsoft):
This is by design and for a good reason. This design helps prevent the Brittle Base Class problem. C# was designed to make it easier and safer to write "versioned" components, and this rule is a big part of that.
When no inheritance is used, both functions are candidates, and the one that is more specific is used. The winner is the function with the int parameter.

Overriding static variables/methods and using them in base class [duplicate]

This question already has answers here:
Can a static method be overridden in C#?
(3 answers)
Closed 7 years ago.
I have a base class with a protected-level static variable, a protected-level static function, and a public function:
public class BaseClass
{
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/overrides the protected-level variable and function:
public class DerivedClass : BaseClass
{
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 DerivedClass.DoSomething, I want the Size value and DoSomethingElse from the DerivedClass to be used, but the BaseClass values are used instead. Is there a way to make this use the DerivedClass variable and method?
You can't override static members. They belong to the class itself and are not associated with any instance of a class, so the concept is not applicable.

How to make a generic singleton base class C# [duplicate]

This question already has answers here:
What's a good threadsafe singleton generic template pattern in C#
(23 answers)
Closed 9 years ago.
I am trying to create a generic singleton base class like
public class SingletonBase<T> where T : class, new()
{
private static object lockingObject = new object();
private static T singleTonObject;
protected SingletonBase()
{
}
public static T Instance
{
get
{
return InstanceCreation();
}
}
public static T InstanceCreation()
{
if(singleTonObject == null)
{
lock (lockingObject)
{
if(singleTonObject == null)
{
singleTonObject = new T();
}
}
}
return singleTonObject;
}
}
But I have to make constructor as public in derived one.
public class Test : SingletonBase<Test>
{
public void A()
{
}
private Test()
: base()
{ }
}
Compilation Error:
'Test' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'Test'
How can I achieve this?
The problem is your generic constraint where T : class, new(). The new() constraint requires a public, parameterless constructor on T. There is no way around this; you need to provide such a constructor in Permission Controller.
I would avoid this kind of recursive generic pattern. Read this this blog post for a detailed explanation of the pattern and reasons not to use it.
As far as I can tell, you don't need to have any sub-classes of SingletonBase<T>. I can't see anything that a subclass of SingletonBase<T> would be able to add to your code. I would simply rewrite it as
public static class Singleton<T> where T : class, new()
{
...
}
You can then use it as
var test = Singleton<Test>.Instance;
If you want to be able to use Test as a singleton, create it as
public class Test
{
public static T Instance
{
get { return Singleton.Instance<Test>; }
}
}

Categories