How can I override a method of a variable

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By juppi

So In java you can do this:

public class BlaBla {
	
	public String something() {
		return "";
	}
}

public class Program {

	public static void main(String[] args) {
		
		BlaBla blaBla = new BlaBla() {
			@Override
			public String something() {
				return "Hello!";
			}
		};
	}
}

How can I achieve the same thing in C#?

:bust_in_silhouette: Reply From: ferhrosa

AFAIK you can’t do exactly that using C#.

But you may use a Func<T> typed property to have a similar result:

public class BlaBla {
    public Func<string> Something { get; set; } = () => "";
}

public class Program
{
    public static void Main(String[] args)
    {
        var blaBla = new BlaBla()
        {
            Something = () => "Hello!",
        };

        Console.WriteLine(blaBla.Something());
        // Will print "Hello!"
    }
}