alex
alex

Reputation: 5731

Implement abstract method of instance on initialization

There is a way to implement an abstract method of instance on initialization in C# like in Java?

public static abstract class A
{
    public abstract String GetMsg();

    public void Print()
    {
        System.out.println(GetMsg());
    }
}

public static void main(String[] args)
{
    A a = new A()
    {
        @Override
        public String GetMsg()
        {
            return "Hello";
        }
    };

    a.Print();
}

Upvotes: 3

Views: 90

Answers (1)

Matthew Watson
Matthew Watson

Reputation: 109762

No you can't - but you can achieve the same end by using a Func<string>:

using System;

namespace Demo
{
    public sealed class A
    {
        public Func<string> GetMsg { get; }

        public A(Func<string> getMsg)
        {
            GetMsg = getMsg;
        }

        public void Print()
        {
            Console.WriteLine(GetMsg());
        }
    }

    public static class Program
    {
        public static void Main()
        {
            var a = new A(() => "Hello");
            a.Print();
        }
    }
}

Alternatively, if you want to be able to change the GetMsg property after initialization:

using System;

namespace Demo
{
    public sealed class A
    {
        public Func<string> GetMsg { get; set; } = () => "Default";

        public void Print()
        {
            Console.WriteLine(GetMsg());
        }
    }

    public static class Program
    {
        public static void Main()
        {
            var a = new A(){ GetMsg = () => "Hello" };
            a.Print();
        }
    }
}

(This uses c#6 syntax - you'd have to modify it slightly for earlier versions.)

Upvotes: 7

Related Questions