Interfaces with Code in them?

Denaes

Senior Contributor
Joined
Jun 10, 2003
Messages
956
By my understanding, an interface is just a list of public functions/events/parameters/etc.

I used IDisposable and it inserted a whole bunch of code, including a private variable and comments.

Now I understand that it can be useful to have default code, but that isn't what an interface is supposed to do. But I think just being able to send comments with your interface signitures would be enormously helpful.

Any insight on how it's done? I've been digging around the MSDN and Google and havn't found out. I'm probobly just not knowing the proper term to search for.
 
If you build your interface with C#, you can use the XML comment that are actually built within the DLL. (/// thing) You'll be able to add remark and description of every parameters.

If you are using VB.NET... it can only be done with .NET 2.0 (find it stupid).

And last... no... you can't have interfaces with code within them. Interface is like a blueprint that people must follow. There is virual class that allow you to have partial code in there (much more like a incomplete class).

So that's it.

If you have any other questions, feel free to ask!
 
I know how to comment a class, but to put code/comments into an interface is the question.

A blueprint is how I see things, but IDisposable Interface puts public & private code and comments into your class that implements it.

So let me ammend the question to how IDisposable is able to be an Interface and supply both code & comments?
 
I'll need to see your code because when I use interfaces in C#, they dont allow me to have variables, initialization or code within properties or methods.
 
They don't allow me to either, thats why I'm asking.

in VB.Net if you type Implements IDisposable, you get this code:

Visual Basic:
Public Class Class1
    Implements IDisposable

    Private disposedValue As Boolean = False        ' To detect redundant calls

    ' IDisposable
    Protected Overridable Sub Dispose(ByVal disposing As Boolean)
        If Not Me.disposedValue Then
            If disposing Then
                ' TODO: free unmanaged resources when explicitly called
            End If

            ' TODO: free shared unmanaged resources
        End If
        Me.disposedValue = True
    End Sub

#Region " IDisposable Support "
    ' This code added by Visual Basic to correctly implement the disposable pattern.
    Public Sub Dispose() Implements IDisposable.Dispose
        ' Do not change this code.  Put cleanup code in Dispose(ByVal disposing As Boolean) above.
        Dispose(True)
        GC.SuppressFinalize(Me)
    End Sub
#End Region

End Class

The only thing I typed was " Implements IDisposable".

I understand the concept. This defies the concept. But still it would be useful to be able to put comments and regions into the interfaces that will show up when someone implements them. At least all of the developers on my team think it would be very useful.
 
PlausiblyDamp said:
Not sure what you mean by

but IDisposable Interface puts public & private code and comments into your class that implements it.

I'm not being snippy, but thats clear english. Thats exactly what it does. You impliment the interface and it puts the code, comments & regions into the class.

PlausiblyDamp said:
how are you implementing the interface (i.e. what features / tools of visual studio are you using)?

I right-click my project, select New->Class, hit enter (accepting the default Class1.vb Name) press the down arrow (because the curser is to the left of the word Public) which puts me on the the only open line of the class. I type the letters "impliments idisposable" and hit enter and all that text I quoted above appears in my class.

So far it's the only Microsoft Interface that does this, but I've only tried IEnumerable and IList... not exactly a thurough check.
 
It may be clear English but when I wrote the question I hadn't seen your follow on post and as such didn't know what language, version or mechanism you where using to implement the interface. The functionality you are experiencing is specific to VB 2005.

The generally facility itself is refered to as a snippet (these can be found under the install folder for VS and are of a general XML format).

These are just an XML file with a .snippet extension and are documented in the IDE although the mechanics of how they integrate differs between VB and C#.
 
C# 2005 doesn't do it:
C#:
#region IDisposable Members

        public void Dispose()
        {
            throw new Exception("The method or operation is not implemented.");
        }

        #endregion

C# 2003 doesn't do it:
C#:
        #region IDisposable Members

        public void Dispose()
        {
            // TODO:  Add Class1.Dispose implementation
        }

        #endregion

VB 2003 (The worst out of all of them):
Visual Basic:
    Public Sub Dispose() Implements System.IDisposable.Dispose

    End Sub

It looks like this is a new feature for VB.Net in 2005. Once again it seems the IDE does more hand holding for VB. I wonder why? And more importantly...how?

Edit: And plausibly damp posted while I was posting. Snippets make sense. It still is bothersome that so much more work seems to go into C# for things like this. I what about mocking? This code
Visual Basic:
    ' This code added by Visual Basic to correctly implement the disposable pattern.
    Public Sub Dispose() Implements IDisposable.Dispose
        ' Do not change this code.  Put cleanup code in Dispose(ByVal disposing As Boolean) above.
        Dispose(True)
        GC.SuppressFinalize(Me)
    End Sub
would be quite bothersome in that case if you don't actually want to dispose a mock right away. That's the hard part of walking the line between too much help and not enough I suppose.
 
Last edited:
In case you're interested I use the following snippet
Code:
<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippet Format="1.0.0">
  <Header>
    <Title>Class with IDispose</Title>
    <Shortcut>disp</Shortcut>
    <Description>Class that implements the IDispossable pattern.</Description>
    <SnippetTypes>
      <SnippetType>Expansion</SnippetType>
    </SnippetTypes>
  </Header>
  <Snippet>
    <Declarations>
      <Literal>
        <ID>classname</ID>
        <ToolTip>Class name</ToolTip>
        <Default>DisposableClass</Default>
      </Literal>
    </Declarations>
    <Code Language="csharp" Format="CData">
    <![CDATA[class $classname$ : IDisposable
    {
         
      private bool _disposed;
      
      #region "Finalisation and Dispose support"
      ~$classname$()
      {
         Dispose(false);
      }
      public void Dispose()
      {
         Dispose(true);
         GC.SuppressFinalize(this);
      }
      protected void Dispose(bool disposing)
      {
      if (!_disposed)
      {
         if (disposing) 
         {
            //Release non-managed stuff
         }
        //Other cleanup
        
        _disposed = true;
      }
      }
      #endregion
    }]]>
    </Code>
  </Snippet>
</CodeSnippet>

to do the same under c#
 
Plausably, I really didn't mean disrespect with that.

I've been using snippets for a short while... lifesavers in my data access layer of the application I'm working on.

It does make sense that it could be a snippet, but how does implementing an interface cause a snippet to be thrown down?

I'm not against such code really in such an important interface really. It's nice to have it and you can change it if it doesn't suit your needs. If it does suit your needs, then bonus.

I wanted something similar that would not include actual code (though in some cases snippets might be nice) but comments explaining exactly what sort of code should be there, why and how it pertains to the application we're writing.

Including snippets would be fantastic for one job, but thats like tying an interface with a snippet to get a job done easier. It would be better served by having both seperate and using a macro to place all the interface and all the snippets.
 
But what about mocks?

Denaes said:
...comments explaining exactly what sort of code should be there...
But that would defeat the whole purpose of the interface. The whole point is that there isn't an implementation tied to the interface. The best example of this would be when you are creating mock objects for unit testing purposes. It's not up to you, the interface creator, to tell me, the interface user, how to use the interface. All I need to know is the interface and perhaps when certain methods of an interface are expected to be used by other classes.

As an example, say I'm creating a mock of a special text writer where one of the interfaces it implements is IDisposable. Since this is a mock I don't actually want to write out to a file because I need to be able to spoof various file states and conditions, such as a write lock exception, or file not found exception or something. Further, I still want to verify what is written to the file later, so instead of writing out to a file, as was intended by the interface, I store the written data in a string array. Since I'm actually testing a class that uses a class that implements this interface, the Dispose method will be called to clean everything up. But I don't want to actually destroy anything; I just want the mock to act as if it's been destroyed for the class under test. Meanwhile, after the method under test has finished, I go through the list and check to make sure that everything was written as expected. The same methodologies would be applied to a dynamic mock object.

IDisposable might be a bad example but I think I made my point.
 
Denaes said:
but how does implementing an interface cause a snippet to be thrown down
VB just does it for you. The same thing doesn't happen in C# so it must just be a feature of VB. You type "Implements IDisposable" and it throws in a snippet.
 
That’s really interesting to me because just recently I was creating a custom collection that implemented IEnumerable and IDisposable and it didn't do any such thing. No commented code or any snippets. Maybe it is just the order of the implements. I’m going to have to go check this out.
 
Just checked it out, it does if Implements IDisposable is first. But if it's a comma separated list of implements it does not.
 
mskeel said:
But that would defeat the whole purpose of the interface. The whole point is that there isn't an implementation tied to the interface.

I know what an interface is and what it's used for. Placing code to explain when it's called and by what and what to expect doesn't violate that.

Primarily we use the interfaces on Inherited Forms & Datasets, both of which will have methods looking for that interface at specific times. There is nothing wrong with mentioning what will be looking for that interface, why and plausably when.

I'm pretty sure Interfaces are there to serve a purpose, not just to ensure certain methods are there that developer knows nothing about and are just left blank or has the wrong code put in there because the developer doesn't know what to expect.
 
Denaes said:
I'm pretty sure Interfaces are there to serve a purpose, not just to ensure certain methods are there that developer knows nothing about and are just left blank or has the wrong code put in there because the developer doesn't know what to expect.
I guess that's my point -- there really isn't such a thing as wrong code. Again, mock objects are the best example of this.

Say you have a DataAccess class that has an IsConnected Property. Normally, for your production code you would probably check the database or a private variable or something and return whether or not you were connected based on actual connectivity. When unit testing it is important to test both the true and false cases independent of outside sources such as a database (you don't want to have to fire up a DB every time you want to run a quick test do you?) or file. What you do is inherit that interface and hard code in a return value of true or false, use a dynamic mock to tell the mock object what to return, or use some other technique to force the IsConnected property to ALWAYS return the same value even though your DataAccess class isn't actually connected to anything. That isn't really wrong functionality. The class is doing exactly what the user intended it to do -- return false (or true) for IsConnected every time it is run.

It's hard to take away the safety nets and let a developer shoot themselves in the foot -- or at least use an interface in ways you didn't intend it to be used -- but that is why interfaces are so powerful. If you want to supply some functionality with your methods, then make an abstract class. Even then, the developer inheriting your class could always override your implementation and ignore it completely.
 
Back
Top