Generic class with interface : Generic Class « Generics « C# / C Sharp

Home
C# / C Sharp
1.2D Graphics
2.Class Interface
3.Collections Data Structure
4.Components
5.Data Types
6.Database ADO.net
7.Date Time
8.Design Patterns
9.Development Class
10.Event
11.File Stream
12.Generics
13.GUI Windows Form
14.Internationalization I18N
15.Language Basics
16.LINQ
17.Network
18.Office
19.Reflection
20.Regular Expressions
21.Security
22.Services Event
23.Thread
24.Web Services
25.Windows
26.Windows Presentation Foundation
27.XML
28.XML LINQ
C# Book
C# / C Sharp by API
C# / CSharp Tutorial
C# / CSharp Open Source
C# / C Sharp » Generics » Generic ClassScreenshots 
Generic class with interface
Generic class with interface
 
using System;
using System.Collections.Generic;

public interface IShape
{
    double Area {
        get;
    }
}

public class Circle : IShape
{
    public Circledouble radius ) {
        this.radius = radius;
    }

    public double Area {
        get {
            return 3.14 * radius * radius;
        }
    }

    private double radius;
}

public class Rect : IShape
{
    public Rectdouble width, double height ) {
        this.width = width;
        this.height = height;
    }

    public double Area {
        get {
            return width*height;
        }
    }

    private double width;
    private double height;
}

public class Shapes<T>
    where T: IShape
{
    public double TotalArea {
        get {
            double acc = 0;
            foreachT shape in shapes ) {
                acc += shape.Area;
            }
            return acc;
        }
    }

    public void AddT shape ) {
        shapes.Addshape );
    }

    private List<T> shapes = new List<T>();
}

public class Test
{
    static void Main() {
        Shapes<IShape> shapes = new Shapes<IShape>();

        shapes.Addnew Circle(3) );
        shapes.Addnew Rect(75) );

        Console.WriteLine"Total Area: {0}", shapes.TotalArea );
    }
}


           
         
  
Related examples in the same category
1.A simple generic classA simple generic class
2.Declare the generic class.
3.A Generic Class with Two Type ParametersA Generic Class with Two Type Parameters
4.Generic Fields
5.Create relationship between two type parameters
6.Demonstrate the default keywordDemonstrate the default keyword
7.Comparing Instances of a Type ParameterComparing Instances of a Type Parameter
8.'This' Reference for Generic Types
java2s.com  |  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.