Search⌘ K
AI Features

Casting and Explicit Implementation

Explore casting between interfaces and classes in C# and understand explicit interface implementation. Learn to handle method name conflicts when multiple interfaces are used and apply access modifiers for interface members. This lesson helps you write clearer and more maintainable code by leveraging interface contracts effectively.

This lesson covers casting between interfaces and classes, as well as the explicit implementation of interface members. We will use the following interface as an example while exploring different concepts.

C# 14.0
namespace Interfaces;
interface INumeric
{
int ToInt32();
long ToInt64();
}
  • Line 1: We use a file-scoped namespace to organize the types.

  • Line 3: We declare the interface INumeric.

  • Lines 5–6: We define the ToInt32 and ToInt64 method signatures that implementers must provide.

Access modifiers and default implementations

Interface members are public by default to facilitate implementation by other classes. Current C# versions support access modifiers on interface members. For instance, we can make methods or properties private.

We typically use private members only when providing a default implementation for a method directly within the interface.

C# 14.0
namespace Interfaces;
interface INumeric
{
// A default implementation relying on a private helper
int ToInt32()
{
return HelperCalculation();
}
long ToInt64();
private int HelperCalculation()
{
return 0;
}
}
  • Lines ...