I'm reading this blog of .NET Engineering Team
and they have introduced a
new feature of default implementation for Interface
. I'm confused related to its motive other than multiple level inheritance problem of abstract class
. Other than that I'm not able to figure out any other benefit. Consdier the following code:
C# 7 (Not possible to provide method definitions)
interface ILogger
{
void LogData(dynamic data, dynamic logMode);
bool SendStatusEmail(string emailAddress);
}
public class EmployeeLog : ILogger
{
public void LogData(dynamic data, dynamic logMode)
{
throw new NotImplementedException();
}
public bool SendStatusEmail(string emailAddress)
{
throw new NotImplementedException();
}
}
public abstract class Logger
{
public abstract void LogData(dynamic data, dynamic logMode);
public bool SendStatusEmail(string emailAddress)
{
// Email Sending Code
return true;
}
}
public class EmployeeLog : Logger
{
public override void LogData(dynamic data, dynamic logMode)
{
throw new NotImplementedException();
}
}
C# 8 (Possible to provide method definitions)
interface ILogger
{
void LogData(dynamic data, dynamic logMode);
public bool SendStatusEmail(string emailAddress)
{
// Email Sending Code
return true;
}
}
public class EmployeeLog : ILogger
{
public void LogData(dynamic data, dynamic logMode)
{
throw new NotImplementedException();
}
}
public abstract class Logger
{
public abstract void LogData(dynamic data, dynamic logMode);
public bool SendStatusEmail(string emailAddress)
{
// Email Sending Code
return true;
}
}
public class EmployeeLog : Logger
{
public override void LogData(dynamic data, dynamic logMode)
{
throw new NotImplementedException();
}
}
In C# 8
, both abstract class
and interface
can do the same work of providing default implementation to its members. I have following doubts related to it:
If Interface provides default implementation and also supports multiple inheritance, what is the need to abstract class in c# 8?
What will happen in case of this scenario?
:
interface ILogger
{
public bool SendStatusEmail(string emailAddress)
{
// Email Sending Code
return true;
}
}
interface IEmail
{
public bool SendStatusEmail(string emailAddress)
{
// Email Sending Code
return true;
}
}
public class EmployeeLog : ILogger, IEmail
{
}
public class Test
{
EmployeeLog emp = new EmployeeLog();
emp.SendStatusEmail(); //Which function it will refer to?
}