Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# override instance method

Tags:

c#

.net

So basically I have an object that takes instances and adds them to a list. Each instance uses virtual methods, which I need to override once the instance is created. How would I go about overriding methods of an instance?

like image 361
tsturzl Avatar asked Sep 24 '12 19:09

tsturzl


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

Is C language easy?

Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.

What is C and C++ meaning?

C is a function driven language because C is a procedural programming language. C++ is an object driven language because it is an object oriented programming. Function and operator overloading is not supported in C. Function and operator overloading is supported by C++. C is a function-driven language.


1 Answers

You can't. You can only override a method when defining a class.

The best option is instead to use an appropriate Func delegate as a placeholder and allow the caller to supply the implementation that way:

public class SomeClass
{
    public Func<string> Method { get; set; }

    public void PrintSomething()
    {
        if(Method != null) Console.WriteLine(Method());
    }
}

// Elsewhere in your application

var instance = new SomeClass();
instance.Method = () => "Hello World!";
instance.PrintSomething(); // Prints "Hello World!"
like image 53
Justin Niessner Avatar answered Sep 18 '22 12:09

Justin Niessner