This question already has answers here:
Is there any way in C# to override a class method with an extension method?
(4 answers)
Closed 8 years ago.
Is it possible to overwrite instance methods by an extension-methods? For example, I have an assembly (compiled, without sources) and I want to rewrite some behaviour.
I created some code for test:
public class SomeClass
{
public void MyMethod()
{
Console.WriteLine("Instance method is called");
}
}
public static class ExtMethods
{
public static void MyMethod(this SomeClass c)
{
Console.WriteLine("Extention method is called");
}
}
then I try to use:
SomeClass s = new SomeClass();
s.MyMethod();
It's compiled successfully, IntelliSence marks this method as instance (extension method has another icon)
output says
Instance method is called
none note about extention method exists. So, no way to overwrite instance method, right?
Why the behavior of the compiler and VS is such non-informative? If I develop an extension-method and there exists already the same instance method (and I don't know about it), I can spend hours to understand why behavior is different than expected...
No, you cannot override the instance method with extension methods. Hence, the name 'extension' method, you can only extend the instance methods.
An instance method will always override the extension method.
If you want to force to call the extension method, call it as a regular static method:
ExtMethods.MyMethod(yourClassInstance);
About the why VS doesn't tell you it is a duplicate: actually it can't do that. What if you have an extension method on object. Should VS check all classes and their methods if any method is a duplicate? They simply didn't build the check, it is something you should do yourself.
Related
This question already has answers here:
What is the use case for C# allowing to use new on a virtual method?
(3 answers)
Why does calling a method in my derived class call the base class method?
(16 answers)
How to use method hiding (new) with generic constrained class
(2 answers)
Closed 1 year ago.
Two classes, one overrides Object.ToString() and one just hides it:
public class One
{
public override string ToString() => "One";
}
public class Two : One
{
public new string ToString() => "Two";
}
Then, I'm calling ToString in two different ways:
var item = new Two();
Console.WriteLine(item.ToString()); // first way
Print(item); // second way
Where Print is
public static void Print<T>(T item)
=> Console.WriteLine(item.ToString());
As result I get
Two
One
Which is not what I expected. My expected behavour would be that both calls will print the same text — Two. I thought that compiler will understand correctly what type is passed and, according to the type, correct method will be called, as T should be Two.
Acquiring type name proves that it's actually Two, but method resolution still works strangely.
Could you please explain what am I seeing? Is boxing involved somehow?
This question already has answers here:
What is difference between extension method and static method?
(2 answers)
Closed 3 years ago.
Given a Class Definition :
Public Static Class Foo
{
public static void Bar(this string A, string B, string C)
{
}
}
What would be the difference between passing the String Explicitly and Implicitly. Viz.
Foo instanceOfFoo="some value";
$(instanceOfFoo).Bar("b","c");
vs
Foo.Bar("a","b","c");
To clarify basis comments, the project I am working on implements a String Extension Logger, which according to my understanding seems a bad choice given that there are a million records of online orders with a lot of columns as varchar(even order_num is a varchar) that translate to strings.
However, since this is implemented by an architect, who seems to be convinced there would be no performance deterioration in using string extension methods, we are forced to use the String Extension method Logger.
I have taken the example as Foo and Bar, but in reality this is
Logger
.Info
.Error etc
There is no difference other than the syntax, in fact the compiler will translate the implicit extension method call to the explicit call to a static method. Extension methods are just very sweet syntactic sugar.
This question already has answers here:
How do I use reflection to call a generic method?
(8 answers)
Closed 8 years ago.
I have a class name as a string. I can then use the following to create a new instance
var assemblyName = Assembly.GetExecutingAssemble().FullName;
var myObj = Activator.CreateInstance(assName, myClassName);
My issue is that I have the following generic method declaration
public static async Task myMethod<T>(string id) where T:IIdentity //boxing
I cannot call this method via
myMethod<myObj>("hello");
as myObj isn't of type T.
Is there a way that I can create a valid instance of myClassName that can be passed to my generic method?
Try this
public static async Task myMethod<T>(string id, T ident) where T:IIdentity
Call this using
myMethod<IIdentity>("hello", myObj);
Let me know if this helps. You might need to fix the method body of myMethod. If you can't fix it you can edit your post to add the method body and I will edit my post to show you the fix. Cheers!!!
This question already has answers here:
Get derived class type from a base's class static method
(8 answers)
Closed 9 years ago.
I'm trying to get the derived class type from a static method defined in the base class.
The structure looks like:
class BaseClass
{
public static Type GetType()
{
return MethodBase.GetCurrentMethod().GetType();
}
}
class Foo : BaseClass
{
}
I need the code Foo.GetType() to return Foo but it returns BaseClass :(
I have to get type without using generics or initializing an instance.
How can I achieve this?
Why not use typeof(Foo)? Without more context on what you're doing, it looks like that should work perfectly.
Since Foo doesn't redeclare GetType, Foo.GetType() is effectively the same method as BaseClass.GetType(). So when you write Foo.GetType(), the compiler emits a call to BaseClass.GetType(), since BaseClass is the type that actually implements the method.
Anyway, what you're doing doesn't make sense ; if you write Foo.GetType(), you already know that you want it to return Foo, so you can just use typeof(Foo).
This question already has answers here:
Can I add extension methods to an existing static class?
(18 answers)
Closed 9 years ago.
How Can I Make Extension Method For System.IO.Path Class what i mean that i need something like below:
Path.GetExtension(sFilePath)
i want to make method:
Path.GetMimeType(sFilePath)
Extension Method:
public static string GetMIMEType(this Path sPath,string sFilePath)
{
string sExtension = Path.GetExtension(sFilePath).ToLowerInvariant();
if (sExtension.Length > 0 && dicMIMETypes.ContainsKey(sExtension.Remove(0, 1)))
{
return dicMIMETypes[sExtension.Remove(0, 1)];
}
return "unknown/unknown";
}
but when compile above code method get error ('System.IO.Path': static types cannot be used as parameters).
Thanks All,
Path is static, and therefore you cannot create an extension method for it. Extension methods require an instance of an object.
This feature is currently not available. you can add extension methods only to an Instance not to Class itself(static).
Feature request already given to Microsoft Static extension methods in C# 4.0
it is not implemented and They may consider it in future or may not.