Monday, August 29, 2011

Multiple Class Implementations

I'm doing a variety of work in both C# and VB.Net these days (as well as VFP).

Every now and then, I come across helpful concepts in the languages that are likely obvious to most developers but may not be known by all of them. If I find something that is of particular interest, I'll put it under these types of posts.

Today, I had a class that implemented multiple interfaces. Both of these interfaces had a similar method: SetReadOnly. So you have two choices:
1. Create a new interface that this class can implement that has the SetReadOnly interface so I only have to implement the one

2. Create two methods that implement that particular method.

Most people are used to VB.Net's handling for Select Case statements where you can put multiple conditions on one line:

Select
Case "A","B","C"
End Select

What I wasn't aware of was that you can use it for Implements as well.

When you add the "Implements xxxx", VS automatically adds the various functions that you have to implement. So in this case, I received TWO methods:

Public Function SetReadOnly() Implements Interface1.SetReadOnly

and then

Public Function SetReadOnly1() Implements Interface2.SetReadOnly

I asked around briefly if this was necessary. As it turns out, it's not. You can easily do:

Public Function SetReadOnly Implements Interface1.SetReadOnly, Interface2.SetReadonly

End Function

Handy way of reducing code.

No comments: