C# Developers halp!

Discussion in 'Unrelated Discussion' started by BulletMagnet, January 22, 2014.

  1. BulletMagnet

    BulletMagnet Post Master General

    Messages:
    3,263
    Likes Received:
    591
    Can anyone explain when I should use an Interface and when I should use a Class?

    I have this code, after spending an hour to discover that I only needed to delete a single character to make it work.

    I merely needed to change line 19, from;

    Code:
    ServiceHost selfHost = new ServiceHost(typeof(myLib.IService1), baseAddy);
    to
    Code:
    ServiceHost selfHost = new ServiceHost(typeof(myLib.Service1), baseAddy);
    and everything worked. It may be interesting to note that both compile.
  2. cola_colin

    cola_colin Moderator Alumni

    Messages:
    12,074
    Likes Received:
    16,221
    I am not working a lot with C#, but generally Interfaces only define the methods (the Interface so to speak) and Classes also implement behavior. The advantage of this is that you can inherit from as many interfaces as you want, if 2 interfaces both define a method called foo() it will be okay, since there wont be two different implementations competing with each other.
    You cannot inherit from 2 classes at the same time, because it could cause conflicts if both classes define a method foo() with different implementations.

    Your example looks like the ServiceHost wants to know the type of the server it is supposed to offer. It probably will try to create an instance of the given type, which is impossible for an Interface. You can only create instances of classes, since Interfaces miss the actual implementation.
    The ServiceHost uses the Interface here to ask for "some service". The service interface could i.e. have an "answerRequest" method and you can define multiple classes that all implement the Interface and do different things as an answer to the request.
    You then pass it to the ServiceHost, which will use the answerRequest method.
    If the ServiceHost would directly ask for a class it would limit all service-implementations to inherit from that class and would prevent them from inheriting from other classes.
  3. BulletMagnet

    BulletMagnet Post Master General

    Messages:
    3,263
    Likes Received:
    591
    Well, with the line in question, I gave it the actual implementation, not the Interface for it.

    Actually, I gave it the typeof(implementation) which is another layer of WTF for me to comprehend.
  4. cola_colin

    cola_colin Moderator Alumni

    Messages:
    12,074
    Likes Received:
    16,221
    Yes, your correct line gives the implementation, the class. I am not sure how C# works here, but from Java Experience I'd say it uses typeOf to get the type of the class you pass. The ServiceHost will than use reflection to create an instance of that class using it's type and use that instance. That is the part that probably fails if you pass the type of an interface. You cannot create instances of interfaces after all.
    BulletMagnet likes this.
  5. BulletMagnet

    BulletMagnet Post Master General

    Messages:
    3,263
    Likes Received:
    591
    Yeah, that makes a bit of sense.
  6. nofear1299

    nofear1299 Active Member

    Messages:
    294
    Likes Received:
    147
    May be slightly off topic but I was going over interfaces again yesterday, basically the example I got was this:

    Think of having a self driving car. Now the car will have methods in the "car" class to turn, accelerate etc. Now for the car to drive itself it will have to get instructions from the GPS system. Now the GPS needs a way to /talk/ to the car. Thats where the interface will come in. Ie the interface will define the methods needed, without actually implementing them. Ie the interface will have turnLeft, turnRight, break, accelerate. The car class will have it's own implementation of each of the methods and so will the GPS. The GPS and car will not need to know what the other is doing to implement it just that they will do the required action. Think of it as the bridge between. Each class has to implement every method in the interface though.

    A class implements the methods.

    Let me know if that helped^_^
  7. light0

    light0 Member

    Messages:
    59
    Likes Received:
    0
    Out of curiosity what was the error? Was it something like "No method found blah blah blah"?

    EDIT: Also to add, people have said what interfaces do but I don't see anyone saying why it's necessary. So I'll just add that interfaces are commonly used to help decouple code. In other words if a load of code is put behind an interface you can change this code safely so long as you satisfy the interfaces methods, this way you don't need to worry about your changes breaking code on the other side of the interface. So for instance in the car example above we can mess around with the car internals and not have to worry about accidentally breaking functionality in our gps as we can see which methods of the car are called externally i.e the interface methods. (......analogy breaks down a bit)
    Last edited: January 22, 2014
  8. mcodl

    mcodl Member

    Messages:
    150
    Likes Received:
    17
    In general there is usually nothing that forces you to use interface when writing your own code. Interfaces are a form of pattern designed to mainly help reduce class coupling and create a common signature for otherwise unrelated classes. An interface has only headers for methods or properties without an accessor that would define its visibility (as interface implementation MUST be public for the interface paradigm to work).

    A typical example would be IComparable<T> which has the very useful int CompareTo(T other); or something like that (I don't carry the whole .Net framework in my head). This interface is used in List<T> in the Sort() method. So the list doesn't have to care if you're sorting apples, dinosaurs, planets, people, colors.... It can still sort them thanks to the IComparable<T> which the T has to implement.

    For the class decoupling: interfaces are generally used with dependency injection pattern which is very popular in the design of business applications so that you can just replace assemblies with the actual implementation and don't have to recompile a solution with potentially hundreds of projects.

    A class can implement as many interfaces as you want while it can derive from a single base class (which by default is System.Object if not otherwise specified).

    Common base classes on the other hand let you put together logic common to the classes that derive from it. An example would be:
    public abstract class Furniture (base class doesn't have to be abstract, I'm using it as an example as there's no point of ever creating an instance of Furniture type)
    public class Chair : Furniture
    public class Table : Furniture

    Base classes can have whatever you want in them (be it abstract headers or implementation). They just can't be static or sealed (what would be the sense in sealing a base type anyway :) ).

    To simplify: think about the interface paradigm as a wrapper for classes which may be related but often aren't. While base classes are used for things that are closely related but wary in some specific implementation.
  9. BulletMagnet

    BulletMagnet Post Master General

    Messages:
    3,263
    Likes Received:
    591
    The error trapping spits out;

    I can remove the try-catch blocks and get you the unhandled exception, but other than saying what line the error was on, it doesn't shed a lot of light onto the situation.
  10. BulletMagnet

    BulletMagnet Post Master General

    Messages:
    3,263
    Likes Received:
    591
    Okay, time for round two;

    I'm following this tutorial for WCF Event shenanigans. Copying the code as-is, and I'm getting the angry blue squiggles saying I'm doing something very wrong (ala. it won't compile).

    Code:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.ServiceModel;
    
    namespace wcfEventService
    {
        [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
        public class MyPublisher : IMyContract
        {
            static Action m_Event1 = delegate { };
    
            public void SubscribeEvent()
            {
                // this is the problem line.
                IMyEvents subscriber = OperationContext.Current.GetCallbackChannel();
                m_Event1 += subscriber.Event1;
            }
    
            public static void FireEvent()
            {
                m_Event1();
            }
    
            public void DoSomethingAndFireEvent()
            {
                MyPublisher.FireEvent();
            }
        }
    }
    What am I missing? Is it just me being daft, or has there been some important change between .Net 3.0 and .Net 4.0 that means I have to adjust things?

    [EDIT] Forgot to mention, my error list reads:

    [EDIT] I'm super daft. Got up and went away from the 'puter for a few minutes. Came back, re-read the error message. Worked out exactly what was missing. Felt embarrassed to be myself.
    Last edited: January 23, 2014

Share This Page