What is the use of method hiding? [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I am learning C#, but I do not understand what's the use of method hiding? I searched the web but I still don't understand exactly how it works. Can anyone explain how it works?

Method hiding is a technique used to replace a non-virtual method of a base class with new functionality in the child class. It has some nasty behaviour that can easily catch people out. To explain by way of an example:
class BaseClass
{
public void Foo()
{
Console.WriteLine("BaseClass");
}
}
class ChildClass : BaseClass
{
public new void Foo()
{
Console.WriteLine("ChildClass");
}
}
ChildClass obj1 = new ChildClass();
BaseClass obj2 = obj1;
obj1.Foo(); // Prints "ChildClass"
obj2.Foo(); // Prints "BaseClass"
If Foo had been declared virtual, new would not be needed and both obj1.Foo() and obj2.Foo() would have printed ChildClass in the example above.
The only other thing you need to know about it is that these days using inheritance is generally frowned upon (do a search of either "inheritance is evil" or "composition vs inheritance" for reams of info on why this is). You therefore shouldn't need to worry about method hiding (unless someone inflicts it upon you with their old and/or misguided code).

Method hiding refers to Information Hiding which is a very basic pattern generally used in programming. Basically you usually want to achieve a clean separation of your components and implementation details from interfaces.

Related

Question about C# and function prototypes [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I was looking at the TextReader class, but I only see method prototypes, I can't see the definitions anywhere. I'm interested in how things work under the hood and I tried looking for the definition of public void Dispose(); but trying to peek or go to definition in VS2019 just returns me here. Where are they stored?
How is it possible to prototype like this? I tried doing it and it wouldn't allow me. This particular method is not virtual.
I'm guessing by "method prototypes" you mean the headers of the methods, i.e. these things:
public virtual Task<String> ReadLineAsync()
The body of the method (or in your words, "definition") is not shown in Visual Studio. One place you can find them, is https://referencesource.microsoft.com/. For example, here is the source for TextReader.
Note that TextReader is an abstract class. Some of the methods in an abstract class can have no bodies by design (though this is not the case with TextReader). For an interface, all methods have no bodies*. If you want to see the implementations of those abstract methods, you need to go to a concrete implementation. For TextReader, this could be StreamReader.
You can create these so called "prototypes" by creating an interface (though it's not the same kind of thing as the one you see in TextReader):
interface IFoo {
int Method1(string param);
string Method2(string p1, string p2);
...
}

Can we change a function behavior depending where it is called in c#? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I want to change a function behavior depending how we call the function.
Example:
class A {
public B instance;
public void HWorld(){
Console.WriteLine("Hello from A! \n");
}
}
class B { // No modification allowed.
public void HWorld(){
Console.WriteLine("Hello from B! \n");
}
}
static void Main()
{
B b= new B();
A a= new A();
a.instance = b;
b.HWorld(); // PRINT Hello from B!
a.instance.HWorld(); //PRINT Hello from A!
}
So my question is: Is there a way (with Event Handler maybe?) to redirect the call B Hworld() to A Hworld() when called as an instance of a specific class?
Other information: I know *it's an XY probleme *: there is a better way to design what I want to do. But I still want to know if it's possible, and how to do it (I don't mind if it require destroying c# compiler).
This is a minimal example: As it doesn't represent the reality, and it's more a theorical question, please avoid: "You can call a.HWorld()".
EDIT
(after on hold)
The question I asked was clear. It was an XY probleme, but I was asking for this X question and the topic was closed for Y being unclear (of course, it was not my question). I don't want to debate anymore if there is other way to go around. I'll do an other post for question Y.
If the method is also marked virtual, you can make a new class that inherits from B, overrides the method, and get the behavior you want.
If it's not marked virtual, you will not be able to do this.

Should a class with only static methods be static? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I have a class with only static methods. Should the class itself be made static too? Does it matter?
Does it matter?
Making a class static ensures that it can never be instantiated by generating a compiler error should the user attempt to do so. If the class, consisting of only static members, is simply not intended to be instantiated, there is no reason not to make it static. You can choose not to do so, but instances of such a class aren't going to be very useful, and users creating these instances are going to be left quite confused.
On the other hand, if you intend for instances of this class to be created but you expect derived classes to implement their own instance members, chances are that this class should be abstract, rather than static (and perhaps those instance members should be stated upfront via abstract definitions or an interface).
In general: Yes.
You can prevent the programmer to create object instances of a certain class by making the class static. If this is what you intend, then do it. This prevents mistakes, by showing (other collegues, etc.) that the class is not intended to be instantiated.
public static class A
{
// Some static member
}
A a = new A(); // Compilation error

Why doesn't C# allow using parent's constructor by default? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Please, note that I don't ask how to do something. This question is about design decision by language authors.
Let's say you have a base class with constructor and a method:
public class BaseClass
{
public BaseClass(string argument)
{
}
public void SomeMethod()
{
}
}
And you also have derived class that is empty (or, in reality, has other unrelated stuff):
public class DerivedClass : BaseClass
{
public DerivedClass() // Some other constructor not used in the example, just so it will compile
}
So, when you will try to call the method on an instance of the derived class, it will work, but if you try to call the constructor, it will result in compile error:
var d = new DerivedClass("argument"); // error CS1729: The type `DerivedClass' does not contain a constructor that takes `1' arguments
d.SomeMethod(); // Works OK
What is the reason behind this language design decision?
This is because constructors are not inherited.
For more info, see this post for an explanation as to why this is: Why are constructors not inherited?

Which one is better creating object of class or call it through interface [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
public class MyTokenStore: ITokenStore
{
public IToken CreateRequestToken(IOAuthContext context)
{
...some code here...
}
public IToken CreateAccessToken(IOAuthContext context)
{
...some code here...
}
}
Which one of below is better ?
Option1 - ITokenStore x = new MyTokenStore(); OR
Option2 - MyTokenStore x = new MyTokenStore()
What are the advanatges of both ?
Can I restrict user from using Option 2 ?
Users decide for themselves which version they use. The advantage of option 1 is that the user can really instantiate any class that implements the interface. Say you have a helper class that contains a method
DoSomethingVeryUseful(ITokenStore store)
then again that method becomes more useful because it can be called with any object that implements said interface.
The advantage of using option 2 is that your class may contain methods that are not part of the interface, and thus those methods can only be used with option 2.
There is no general good response to this, as it fully depends on you concrete case.
ITokenStore x = new MyTokenStore()
mades a "slice" over concrete MyTokenStore instance where not all members are inside ITokenStore, so you missing access to some additional information that may be present in MyTokenStore and is not present in ITokenStore.
On other hand you create an abstraction layer, so gain a flexibility.
The purpose of an interface is to expose functionality that is common to all implementer's and is agnostic of the concrete implementation. If you are trying to pass around multiple concrete objects to a consumer that needs to access an interface method, then cast it as an interface.
However, if you need a specific member on the concrete implementation, use that.
This is not which is better question but more what are you going to do with it ? Somethings to consider
Are you going to have multiple objects implement the interface ?
Are you going to be doing unit testing ?
Are you going to be doing any in Dependency Injection ?
If you can answer yes to at least one of the questions the using a interface is a good idea but if your using a interface just to use a interface you might want to rethink the solution
My suggestion is the below option. Instead creating "new" object, we can go with contructor injection.
public class MyTokenStore{
private readonly ITokenStore;
public MyTokenStore{ITokenStore TokenService)
{
this.TokenStore=TokenService;
}
}

Categories

Resources