Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement abstract method of instance on initialization

Tags:

c#

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();
}
like image 815
alex Avatar asked Apr 16 '26 02:04

alex


1 Answers

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

like image 137
Matthew Watson Avatar answered Apr 17 '26 15:04

Matthew Watson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!