Is there a simple way to implement this, and if possible without instanciating an object :
interface I
{
static string GetClassName();
}
public class Helper
{
static void PrintClassName<T>() where T : I
{
Console.WriteLine(T.GetClassName());
}
}
Try an extension method instead:
public interface IMyInterface
{
string GetClassName();
}
public static class IMyInterfaceExtensions
{
public static void PrintClassName<T>( this T input )
where T : IMyInterface
{
Console.WriteLine(input.GetClassName());
}
}
This allows you to add static extension/utility method, but you still need an instance of your IMyInterface implementation.
You can't have interfaces for static methods because it wouldn't make sense, they're utility methods without an instance and hence they don't really have a type.
You can not inherit static methods. Your code wouldn't compile in any way, because a interface can't have static methods because of this.
As quoted from littleguru:
Inheritance in .NET works only on
instance base. Static methods are
defined on the type level not on the
instance level. That is why overriding
doesn't work with static
methods/properties/events...
Static methods are only held once in
memory. There is no virtual table etc.
that is created for them.
If you invoke an instance method in
.NET, you always give it the current
instance. This is hidden by the .NET
runtime, but it happens. Each instance
method has as first argument a pointer
(reference) to the object that the
method is run on. This doesn't happen
with static methods (as they are
defined on type level). How should
the compiler decide to select the
method to invoke?
I also tried to setup a static method on an interface a little while ago, not sure why now. I did bookmark this so maybe it helps:
Interface with a static method by using extension methods
If you're just after the type name, you can just do this:
public class Helper
{
static void PrintClassName<T>()
{
Console.WriteLine(typeof(T).Name);
}
}
Declaring a static property, event or method on an interface definition is not considered a legal definition. This is because interfaces are considered contracts and as such, represent something that will be implemented by every client instance of that interface.
A static declaration essentially states that the static member does not require a physical client implementation in order to execute the required functionality and this falls short of the general concept of interfaces: providing a proven contract.
The answer is a qualified "not really but Sort Of". You can provide a static extension method to all implementors of a given interface and can then call this from your implementer in a property or another method. As an example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace InterfacesWithGenerics
{
class Program
{
static void Main(string[] args)
{
Helper.PrintClassName<Example>(new Example());
Console.ReadLine();
}
}
public class Example : I
{
#region I Members
public string ClassName
{
get { return this.GetClassName(); }
}
#endregion
}
public interface I
{
string ClassName { get; }
}
public class Helper
{
public static void PrintClassName<T>(T input) where T : I
{
Console.WriteLine( input.GetClassName()) ;
}
}
public static class IExtensions
{
public static string GetClassName(this I yourInterface)
{
return yourInterface.GetType().ToString();
}
}
}
Here we have an interface (I) which defines the property we care about and a static extension method (GetClassName) which is applied to all members of its type which does the grunt work of getting the information we want. We Have a Class (Example) which implements the I interface so when we call our static helper class passing in an instance of Example, it runs the static method against it. Unfortunately it is not valid to reference the type T directly within the method itself as a variable, you'll have to pass an instance into the application.
You could define the className as attribute on the specific class. This is the preferred ay to store metadata in .net. This way you can query the attribute for the given class and you do not need an instance.
Yes, you can - sort-of - if you don't mind defining new types that proxy instance calls to static methods:
While an interface can only declare instance members, you can use a couple of simple tricks with C#'s generics, without needing reflection, to accomplish what you're after (and without resorting to Java-style AbstractFactoryBeanFactory design-pattern overuse).
What we can do, is define a separate struct (i.e. a value-type) that contains instance members that call-into the static members we want.
So if we have this interface:
interface IStaticFunctionality
{
void DoSomethingWithoutAnObjectInstance();
}
...and we want to do something like this:
void AGenericMethodThatDoesntHaveAnInstanceOfT<T>()
{
T.DoSomethingWithoutAnObjectInstance();
}
...then we can do this:
void AGenericMethodThatDoesntHaveAnInstanceOfT<T>()
where T : struct, IStaticFunctionality
{
T t = default;
t.DoSomethingWithoutAnObjectInstance();
// Note the above code uses `T t default;` instead of `T t = new T()`.
// This is because the C# compiler currently replaces `new T()` with `Activator.CreateInstance<T>()` in the generated bytecode.
// This has poor performance compared to `default(T)` or a normal non-generic constructor call, but the compiler does this because it's a workaround for a design-bug back in C# 6.0: https://devblogs.microsoft.com/premier-developer/dissecting-the-new-constraint-in-c-a-perfect-example-of-a-leaky-abstraction/
}
So if we have different types with the static void DoSomethingWithoutAnObjectInstance method, we just need to define struct implementations of IStaticFunctionality for each of those types:
class Foo
{
public static void DoSomethingWithoutAnObjectInstance()
{
Console.WriteLine("foo");
}
struct Static : IStaticFunctionality
{
void DoSomethingWithoutAnObjectInstance() => Foo.DoSomethingWithoutAnObjectInstance();
}
}
class Bar
{
public static void DoSomethingWithoutAnObjectInstance()
{
Console.WriteLine("bar");
}
struct Static : IStaticFunctionality
{
void DoSomethingWithoutAnObjectInstance() => Bar.DoSomethingWithoutAnObjectInstance();
}
}
So then a call-site for AGenericMethodThatDoesntHaveAnInstanceOfT<Foo> would actually look like:
AGenericMethodThatDoesntHaveAnInstanceOfT<Foo.Static>();
Related
I was wondering if it's possible (even via reflection et similia) to get the caller derived-class inside of a called base-class static method.
For example, I've a base-class with a static method defined:
public MyBaseClass {
public static void MyBaseClassStaticMethod() { /** ... **/ }
}
and a derived-from-it class:
public MyDerivedClass : MyBaseClass { }
then I call:
MyDerivedClass.MyBaseClassStaticMethod()
Is it possibile, inside of method MyBaseClassStaticMethod, to know which is the caller derived type?
(i.e. MyDerivedClass)
I just need a string...
Generics in following way can be used to solve your scenario
public class BaseClass<TDerived> where TDerived : BaseClass<TDerived>
{
public static void LogCallerType()
{
Console.WriteLine(typeof(TDerived).Name);
}
}
public class FooClass : BaseClass<FooClass> { }
public class BooClass : BaseClass<BooClass> { }
class Program
{
static void Main(string[] args)
{
FooClass.LogCallerType();
BooClass.LogCallerType();
}
}
This will in turn output the following
1. FooClass
2. BooClass
No, this is not possible - by no means. static methods are not polymorphal and as such this information simply doesn't exist.
Consider redesigning your code.
Update:
Upon compilation, the compiler replaces MyDerivedClass with the class the static method is actually declared on, in your case MyBaseClass.
So even in the IL you don't see MyDerivedClass. The information exists only in your source code. It doesn't exist in your compiled assembly.
A static method is statically bound to a certain class and does not really participate in the inheritance-chain. Thus it does not exist in the derived class. The static method therefor does not know that it was actually used in the derived class.
You can however - through a compiler-trick - access the static member from your derived class. As of this post on MSDN-forum a static member-access from a derived class is translated to a call from the base-class containing the static member. So MyDerivedClass.MyBaseClassStaticMethod is translated to MyBaseClass.MyBaseClassStaticMethod. Thus MethodBase.GetCurrentMethod().DeclaringType will allways return MyBaseClass.
So in short: no, it´s not possible to get the derived type from a static member.
First of all, the static method will not have access to the instance that is calling it. A static method is different from a normal class method in that it does not have access the 'this' reference to a class instance.
If you passed 'this' as a parameter to the static method, then you can try casting it as follows. Assume you have a number of derived class which you want to test for.
public static void MyBaseClassStaticMethod(MyBaseClass callingInstance)
{
MyDerivedClass myDerivedClass = callingInstance as MyDerivedClass;
MyDerivedClass2 myDerivedClass2 = callingInstance as MyDerivedClass2;
MyDerivedClass3 myDerivedClass3 = callingInstance as MyDefivedClass3;
...
// test for which derived class is calling
if (myDerivedClass != null)
...
else if (myDerivedClass2 != null)
...
...
}
Not a fan of Java, but Java allows not setting types for generic classes and in that case it threats the type as Object type. However, as far as I know, C# enforces setting the type of <T> anytime the generic class has to be instantiated or simply speaking used. However, let's say that we have a generic class, and we need a static method in there which does not rely on the type of <T>.
Firstly, we know that it can be moved to a separate context or we can set a dummy type of <T>, but as a programming puzzle is there any way to call it Without defining the type of T?
Example:
class Test<T> where T: ITestable {
...
public static void CreateTestFile(String fileName) {...}
}
Test.CreateTestFile("test.txt");
This can be done Java and apparently can't be in C#. But I just wanna make sure.
Java and C# implement generics differently:
Java uses type erasure, which basically means that at compile time, anything you put in <T> is erased and becomes Object. Something<Foo> and Something<Bar> will be the same type at runtime, and wil be effectively equal to Something<Object>.
C# uses run-time reification, meaning that for each type you use with a distinct T, the runtime generates a new class altogether, by using the open generic version as a template (which means it also generates the underlying native code once per T as you call it). Something<Foo> and Something<Bar> are two unrelated types as far as the CLR is concerned.
Hopefully you understand why this difference is important to your scenario. Ignoring T is trivial in Java, but not so easy in C#.
If you don't need T in your code, then use a non-generic method:
abstract class Test
{
public static void CreateTestFile(String fileName) {...}
}
class Test<T> : Test
where T : ITestable
{
...
}
Here, that's better :)
Also, note that for instance methods, you can use covariant and contravariant interfaces to loosen the requirement for a known T at compile-time. For instance, if you use a covariant interface, you only need to know a base type of T.
You should really consider separating your concerns, placing that public static method elsewhere. However, if you really want to call it, this would work just fine:
class Program
{
static void Main(string[] args)
{
Test<ITestable>.CreateTestFile("test.txt");
}
}
class Test<T> where T : ITestable
{
public static void CreateTestFile(String fileName) { }
}
public interface ITestable { }
If you had a constraint where T : class, new(), you could do something similar:
class Program
{
static void Main(string[] args)
{
Test<object>.CreateTestFile("test.txt");
}
}
class Test<T> where T : class, new()
{
public static void CreateTestFile(String fileName) { }
}
public interface ITestable { }
If you had an even weirder constraint like where T : class, ITestable, new() I'd stop worrying about getting the compiler to jump through your hoops, rethink your design, and separate the concerns along these lines:
class Program
{
static void Main(string[] args)
{
Util.CreateTestFile("test.txt");
}
}
class Util
{
public static void CreateTestFile(String fileName) { }
}
class Test<T> where T : class, ITestable, new()
{
/*...*/
}
public interface ITestable { }
I was wondering if it's possible (even via reflection et similia) to get the caller derived-class inside of a called base-class static method.
For example, I've a base-class with a static method defined:
public MyBaseClass {
public static void MyBaseClassStaticMethod() { /** ... **/ }
}
and a derived-from-it class:
public MyDerivedClass : MyBaseClass { }
then I call:
MyDerivedClass.MyBaseClassStaticMethod()
Is it possibile, inside of method MyBaseClassStaticMethod, to know which is the caller derived type?
(i.e. MyDerivedClass)
I just need a string...
Generics in following way can be used to solve your scenario
public class BaseClass<TDerived> where TDerived : BaseClass<TDerived>
{
public static void LogCallerType()
{
Console.WriteLine(typeof(TDerived).Name);
}
}
public class FooClass : BaseClass<FooClass> { }
public class BooClass : BaseClass<BooClass> { }
class Program
{
static void Main(string[] args)
{
FooClass.LogCallerType();
BooClass.LogCallerType();
}
}
This will in turn output the following
1. FooClass
2. BooClass
No, this is not possible - by no means. static methods are not polymorphal and as such this information simply doesn't exist.
Consider redesigning your code.
Update:
Upon compilation, the compiler replaces MyDerivedClass with the class the static method is actually declared on, in your case MyBaseClass.
So even in the IL you don't see MyDerivedClass. The information exists only in your source code. It doesn't exist in your compiled assembly.
A static method is statically bound to a certain class and does not really participate in the inheritance-chain. Thus it does not exist in the derived class. The static method therefor does not know that it was actually used in the derived class.
You can however - through a compiler-trick - access the static member from your derived class. As of this post on MSDN-forum a static member-access from a derived class is translated to a call from the base-class containing the static member. So MyDerivedClass.MyBaseClassStaticMethod is translated to MyBaseClass.MyBaseClassStaticMethod. Thus MethodBase.GetCurrentMethod().DeclaringType will allways return MyBaseClass.
So in short: no, it´s not possible to get the derived type from a static member.
First of all, the static method will not have access to the instance that is calling it. A static method is different from a normal class method in that it does not have access the 'this' reference to a class instance.
If you passed 'this' as a parameter to the static method, then you can try casting it as follows. Assume you have a number of derived class which you want to test for.
public static void MyBaseClassStaticMethod(MyBaseClass callingInstance)
{
MyDerivedClass myDerivedClass = callingInstance as MyDerivedClass;
MyDerivedClass2 myDerivedClass2 = callingInstance as MyDerivedClass2;
MyDerivedClass3 myDerivedClass3 = callingInstance as MyDefivedClass3;
...
// test for which derived class is calling
if (myDerivedClass != null)
...
else if (myDerivedClass2 != null)
...
...
}
I know this question has been asked over and over, but I can't seem to find good enough answers. So to make it clear what I'm trying to know, I'll split this in two questions:
Why can't interfaces have static method signatures? I'll try to preempt the non-answers asking why in the world I would want to do this with the following: I would want to be able to statically invoke GetDbConnectionType() on SqliteCodeGenerator and MssqlCodeGenerator:
interface ICodeGenerator
{
// this is the method I would like to be static:
string GetDbConnectionType();
}
abstract class CodeGeneratorBase : ICodeGenerator
{
public abstract string GetDbConnectionType();
public void GenerateSomeCode(StringBuilder s)
{
s.AppendLine("var foo = new " + GetDbConnectionType() + "();");
}
}
class SqliteCodeGenerator : CodeGeneratorBase
{
public override string GetDbConnectionType()
{
return "SQLiteConnection";
}
}
class MssqlCodeGenerator : CodeGeneratorBase
{
public override string GetDbConnectionType()
{
return "SqlConnection";
}
}
On the other hand, and this is the matter of this second question, if you know of a good alternative to reach the aforementioned goal, then by all means...
Suppose you could specify in an interface that a type had to have a particular static method... how would you call it? Polymorphism works through instances - whereas static members explicitly don't use instances.
Now, having said that, there's one situation in which I can see static interface members working: generic types. For example:
// This isn't valid code...
public void Foo<T>() where T : ICodeGenerator
{
string type = T.GetDbConnectionType();
}
That would call the static member on the concrete type T.
I've blogged more about this, but I suspect the benefit doesn't justify the complexity.
In terms of alternatives - usually you'd have another interface, and have separate types to implement that interface. That works well in some contexts, but not in others.
#JonSkeet: It's possible to create a static interface member in CIL, so I'm afraid your first statement is misleading. I assume it was omitted from C# as a design choice by the Microsoft team to encourage correct usage of interfaces.
The best way to get this functionality is probably with extension methods, these will allow you to add a method to all inheritors of your interface or to a specific implementation of that interface however you need to write a separate class to hold the implementation of the extension method which (if not planned for) can be easy to lose track of.
Jon's answer covers pretty much everything so my answer only includes a possible work around using the .NET configuration API. It requires a bit of syntax overhead but it does give you static access to the instance.
interface IStorage
{
void Store(string item);
}
static class Storage
{
private static readonly IStorage _instance;
static Storage()
{
var storageTypeString = ConfigurationManager.AppSettings["storageTypeString"];
var storageType = Type.GetType(storageTypeString, true);
_instance = (IStorage)Activator.CreateInstance(storageType);
}
public static void Store(string item)
{
_instance.Store(item);
}
}
It might be somewhat helpful if an interface could specify a static class, such that members of that class would be seen by the compiler as static members of that interface. Thus, instead of having to use static class Enumerable<T> to get Enumerable<T>.Default, one could instead syntactically specify IEnumerable<T>.Default.
It would be even more helpful if an interface could specify that some such static methods should be usable in a fashion similar to extension methods, but without the weird scoping rules associated with them (so an interface could appear to offer multiple "convenience" overloads for some member functions without requiring all of the implementations to provide them).
It would be extremely helpful if, combined with such a feature, interface methods could be declared "optional", such that when an implementation provided a method it would be used, and when it did not the extension-ish method would be automatically substituted. This would probably require changes to the CLR, however.
In any case, because interfaces do not include static classes, the best one can do is provide static classes which users of the interface will find helpful, even though the compiler will regard those classes and the interfaces as entirely independent entities.
I know this is old, but actually you can with static functions declared in a static class outside of a name space.
but they way your putting it you would just make the function static in the abstract class
to do it from an interface you do this
public static class Interfacefunction{
public static string GetDbConnectionType(this ICodeGenerator me)
{
// this is the method I would like to be static:
// you can even get access to me
return "SQLiteConnection";
}
}
A sort of workaround (though it may actually be better this way) for this I've decided to use is to use a static instance instead of a static interface.
Rather than:
// does not compile
ISomeInterface {
static void DoSomething();
static bool TestSomething(string pValue);
// etc...
}
static class SomeStaticClass : ISomeInterface {
public static void DoSomething() {
}
public static bool TestSomething(string pValue) {
}
}
Define a class (make it generic if the logic must vary between classes that you use it with):
sealed class SomeClass {
public void DoSomething() {
// reusable implementation
}
public bool TestSomething(string pValue) {
// reusable implementation
}
}
and give a static instance of that class to your static class:
static class SomeStaticClass {
static readonly SomeClass sSomeClass = new SomeClass();
}
The only issue is that you have to decide whether to expose a property to the static instance:
static class SomeStaticClass {
static readonly SomeClass sSomeClass = new SomeClass();
public static SomeClass SomeProperty { get { return sSomeClass; } }
}
...
SomeStaticClass.SomeProperty.DoSomething();
if (SomeStaticClass.SomeProperty.TestSomething(someValue))
...
or to wrap its methods:
static class SomeStaticClass {
static readonly SomeClass sSomeClass = new SomeClass();
public static void DoSomething() {
sSomeClass.DoSomething();
}
public static bool TestSomething(string pValue) {
sSomeClass.TestSomething(pValue);
}
}
...
SomeStaticClass.DoSomething();
if (SomeStaticClass.TestSomething(someValue))
...
So something like:
public static class StaticClass {}
public class InstanceClass
{
static StaticClass StaticProperty {get;set;}
public InstanceClass()
{
InstanceClass.StaticProperty = StaticClass;
}
}
I thought one could do this but the compiler returns these errors:
static types cannot be used as parameters
static types cannot be used as return types
EDIT: I know that this doesn't work, but why? I imagine StaticClass is stored somewhere in memory, so other variables could be allowed to refer to it at the same memory, right?
EDIT2: One of the use cases would be something like this:
Say you have 5 different static classes you have collected with no source code, and they do generic stuff, so you want to have convenient access to them through a single static class. You could do it like:
public static class GenericStuff
{
public LinearAlgebra LinearAlgebra {get;set;}
public StringUtilities String {get;set;}
public GeometryOps Geometry {get;set;}
}
And use it like:
GenericStuff.LinearAlgebra.GetAngleBetweenVectors(v0, v1);
Some other use cases you could think of.
Update: I am going to use my psychic powers to try and figure what I think you're trying to do.
I'm guessing you have a static class with some methods that you want to access from within another class. Is that right?
Something like this, in other words:
static class HelperMethods
{
public static void SomeHelperMethod();
}
...and what you want to do is something like this?
class SomeOtherClass
{
public void MethodThatUsesHelperMethod()
{
// You want to be able to have "Helper" mean "HelperMethods"?
Helper.SomeHelperMethod();
}
}
If I've interpreted you correctly, there's only one way (that I can think) to sort of accomplish what you're after. This would be to add a using declaration to effectively alias your static type:
// At top of file
using Helper = HelperMethods;
Note that if you do this, you're creating a file-wide alias. There's no way to alias classes at only the class level.
StaticClass is the name of the class. Your StaticProperty property expects an instance of the class, which will never exist because the class is static.
I'm actually surprised you can even have a property typed as a static class, since it represents a total impossibility. (Oh wait, you can't do that; that's what you were saying.)
You say you want to store a "reference to a static class"; I have to assume you mean that you want a reference to the Type object representing the class, in which case you should do this:
public Type StaticProperty { get; set; }
// ...
StaticProperty = typeof(StaticClass);
Static classes are both abstract and sealed (take a peek at the generated IL). So, you can't create an instance of it, and you can't subclass it to have instances of subclasses. That combination alone makes it impossible for you to ever have a reference to an instance of a static class.
Now, to have a reference to the static class work the way you want, you'd have to have metaclasses in C#, or some different kind of aliasing.
To achieve what you want today, you'd have to manually delegate all methods from a wrapper class to the desired static class, or abandon static typing and use dynamic:
public class StaticWrapper : DynamicObject {
Type _type;
public StaticWrapper(Type type) {
_type = type;
}
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) {
var method = _type.GetMethod(binder.Name, BindingFlags.Static | BindingFlags.Public, null, args.Select(a => a.GetType()).ToArray(), null);
if (method == null) return base.TryInvokeMember(binder, args, out result);
result = method.Invoke(null, args);
return true;
}
// also do properties ...
}
Usage:
public static class GenericStuff {
public readonly dynamic LinearAlgebra = new StaticWrapper(typeof(LinearAlgebra));
public readonly dynamic String = new StaticWrapper(typeof(StringUtilities));
public readonly dynamic Geometry = new StaticWrapper(typeof(GeometryOps));
}
Section §8.7.12 of the C# specification reads:
Classes that are not intended to be
instantiated, and which contain only
static members should be declared as
static classes. Examples of such
classes are System.Console and
System.Environment. Static classes
are implicitly sealed and have no
instance constructors. Static classes
can be used only with the typeof
operator and to access elements of the
class. In particular, a static class
cannot be used as the type of a
variable or be used as a type argument
Because a static class has no constructors, you can't instantiate it. Because it is sealed you cannot subclass it and create an instance of a subclass. Even if you could subclass it you wouldn't be able to call the base constructor, and therefore you still couldn't instantiate it.
Since you cannot create an object of the type of a static class, it makes no sense to use it as a return type.
Since StaticClass is a type name, not an expression, you cannot pass it as a parameter (in your case, to the property setter). However, you can obtain an instance of the Type class that represents it with the expression typeof(StaticClass).
You cannot store a reference to a static class. You can only store references to instances, and there are no instances of static classes (although static classes may have instance members).
You should take another look at the MSDN page on static classes.
"A static class is basically the same as a non-static class, but there is one difference: a static class cannot be instantiated. In other words, you cannot use the new keyword to create a variable of the class type. Because there is no instance variable, you access the members of a static class by using the class name itself."
I think this is what you are trying to say:
Ok, if you don't want to instantiate it, then your C# needs a bit more tweaking. Assuming your static class implements a property and/or method
public static class StaticClass
{
public static string StaticProperty {get; private set; }
public static void StaticMethod() { //DoSomething }
}
You can forward the property and function definitions in the InstanceClass, notice that you must prefix the class name of the static to the methods/properties that you want to call.
public class InstanceClass
{
private string StaticProperty
{
get { return StaticClass.StaticProperty; }
}
private StaticMethod()
{
StaticClass.StaticMethod();
}
public InstanceClass()
{ }
}
I think that using InstanceClass as a wrapper like this is a bit complicated, and unecessary. I've found that its worth trying to minimize the need for static classes and methods in a codebase. They cause all sorts of headaches when trying to test and debug.
I believe using the namespace feature would be the best way to accomplish what you're trying to do.
LinearAlgebra.cs
namespace GenericStuff
{
public static class LinearAlgebra
{
public static TypeOfResult Function() { ... }
}
}
Strings.cs
namespace GenericStuff
{
public static class Strings
{
public static TypeOfResult Function() { ... }
}
}
Geometry.cs
namespace GenericStuff
{
public static class Geometry
{
public static TypeOfResult Function() { ... }
}
}
All of which can be invoked starting with GenericStuff
var s = GenericStuff.Strings.Random(7);
var identity = GenericStuff.LinearAlgebra.Identity(3);
var square = GenericStuff.Geometry.Square(5);
var area = square.Area();
You can't do this. A class is not an instance of itself. "Dog" is not a Dog. You could assign typeof(StaticClass) to a field of type Type:
static StaticClass StaticProperty {get; set}
InstanceClass.StaticProperty = typeof(StaticClass);
This lets you use reflection on the type.
What I believe the op wants is a way to access other classes easily via a "proxy" that you know of.
So, lets say you have a class called MapHelpers:
public class MapHelper
{
public static string CalculateNearLocation (Vector3 position){...}
}
And you have many other "Helpers" that you don't really remember and just want to have them easily accessible. And so, you want to "store" them inside your "Helpers" class, just so you can remember where you put them.
You can either do this :
public class Helpers
{
public class MapHelpers : MapHelper{}
}
And be able to access your MapHelper via :
Helpers.MapHelpers.CalculateNearLocation(pos)
Or do this :
public partial class Helpers
{
}
public partial class Helpers
{
public class MapHelper
{
public static string CalculateNearLocation (Vector3 position){...}
}
}
And be able to access it via :
Helpers.MapHelper.CalculateNearLocation(pos)
However, the first method, will give you a warning on your IDE (if you have that set) about accessing static methods via derived type.
Depends on what you want to achieve in the end.
If you want to just change one class but not on runtime but on compile time (i.e. the same version of static file is going to be used), then you can easily just configure your app or just make several versions of the same file with various implementations.
Such approach is useful for e.g. translations if you have them in a static files.