✅ Default interface methods - Am I using them wrong?

I'm trying to learn when/where to properly use interfaces, and I don't understand why my default method doesn't work. I have this:
c#
public interface IMyInterface {
string Name { get; set; }
string JobTitle { get; set; }

void Foo() { Console.WriteLine("Default Foo"); }
}

public class Person {
public string Name { get; set; }
}

public class Employee : Person, IMyInterface {
public string JobTitle { get; set; }
}
c#
public interface IMyInterface {
string Name { get; set; }
string JobTitle { get; set; }

void Foo() { Console.WriteLine("Default Foo"); }
}

public class Person {
public string Name { get; set; }
}

public class Employee : Person, IMyInterface {
public string JobTitle { get; set; }
}
Creating a new instance of Employee should give me access to employee.Foo(), but it doesn't. Maybe I'm just overlooking something simple, but I don't understand :/
6 Replies
UnemployedNinja
UnemployedNinjaOP2mo ago
I'm using .net6
Jimmacle
Jimmacle2mo ago
you can only access DIMs by casting the object to the interface that being said, you shouldn't use DIMs for this they were added to the language mostly as a way to add new methods to interfaces in a backwards compatible way
UnemployedNinja
UnemployedNinjaOP2mo ago
So DIM's are generally not very good practice to use?
becquerel
becquerel2mo ago
they are a tool meant for things like authors of libraries not so much normal application code
UnemployedNinja
UnemployedNinjaOP2mo ago
!close
Accord
Accord2mo ago
Closed!
Want results from more Discord servers?
Add your server