`new` modifier works unexpectedly inside a generic method call [duplicate] - c#

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?

Related

Is there any workaround for CS0266: Cannot implicitly convert type ... (IList<Interface>)? [duplicate]

This question already has answers here:
Cast List<T> to List<Interface>
(10 answers)
Closed 3 years ago.
I have a class which implements an interface. A second class implements an IList<> of this first class. I need to assign this second class to a generic property which is an IList<> of the interface.
This is a demo for the code I use:
public class SODemo
{
public SODemo()
{
ClassWithIListOfClassWithInterface classWithIList = new ClassWithIListOfClassWithInterface();
IList<IDemoInterface> listOfInterfaces;
// CS0266: Cannot implicitly convert type ...
listOfInterfaces = classWithIList;
}
}
public class ClassWithInterface : IDemoInterface
{
// ...
}
public class ClassWithIListOfClassWithInterface : IList<ClassWithInterface>
{
// ...
}
From answers on similar problems I found out that it seems not work at all.
Why do I need this?
I have a lot of classes which are implemented like ClassWithIListOfClassWithInterface and I need a generic handler for them.
Question:
My goal is to access each element in listOfInterfaces through the methods implemented in the interface.
Is there any alternative I can use?
Edit
I already tried this
listOfInterfaces = (IList<IDemoInterface>)classWithIList;
but then I get an System.InvalidCastException at runtime.
The problem is not with your class itself, but rather with the conversion between IList<IDemoInterface> and IList<ClassWithInterface>.
IList<T> in C# are said to be "invariant in T". This means that you cannot make conversions between IList<T1> and IList<T2> directly, even if they have an inheritance relationship.
What you can do is to create an IList<IDemoInterface> and copy every element from your source IList<ClassWithInterface> to it. Of course that'd be rather cumbersome, so the LINQ way of doing it is that:
listOfInterfaces = classWithIList.Cast<IDemoInterface>().ToList();

Invocation of a String Extension Method on a String vs Passing the String as a Parameter [duplicate]

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.

Why to use Overriding? [duplicate]

This question already has answers here:
C# virtual keyword
(9 answers)
C# - Keyword usage virtual+override vs. new
(11 answers)
Can you write virtual functions / methods in Java?
(6 answers)
Closed 4 years ago.
In an interview it was asked why do we need to override method of base class.
I tried to answer like when we want to have different implementation in derived class.
But then he said, "Why don't we just create a new method with different name and different implementation instead of overriding base class method?", anyway we are not reusing base class method as implementation will be different then just create a new method instead of overriding.
I got confused what to answer. Could somebody explain.
public class BaseClass
{
virtual void Foo(){}
}
public class DerivedClass: BaseClass
{
override void Foo(){}
}
Generally we implement overriding like above.
What he said is like why do we need concept of overriding we can do like below
public class BaseClass
{
void Foo(){}
}
public class DerivedClass: BaseClass
{
void Foo1(){}
}
His question was looking weird I tried to explain but like its a method of base class we are just redefining it in derived class. In this way our code will be clean as well. But looks like he was not satisfied.
I would check this answer:
Why does this polymorphic C# code print what it does?
then try to grasp the concept of methods in an object basically having pointers to code. When you override implementation in an subclass then that becomes the new code pointed to, whether it's used or cast as a superclass or not.
So the main purpose of overriding is to create classes that inherit from one class but each have their own implementation and then be able to treat or operate on them equally the same as the original superclass. This is the essence of the Liskov Principle or the 'L' in SOLID. What is an example of the Liskov Substitution Principle?

Can Extension-Methods overwrite instance methods? [duplicate]

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.

Get class type from static method (on base class) [duplicate]

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).

Categories

Resources