✅ 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
UnemployedNinjaOP2w ago
I'm using .net6
Jimmacle
Jimmacle2w 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
UnemployedNinjaOP2w ago
So DIM's are generally not very good practice to use?
Becquerel
Becquerel2w ago
they are a tool meant for things like authors of libraries not so much normal application code
UnemployedNinja
UnemployedNinjaOP2w ago
!close
Accord
Accord2w ago
Closed!
Want results from more Discord servers?
Add your server