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.Design Patterns
8.Development Class
9.Event
10.File Stream
11.Generics
12.GUI Windows Form
13.Language Basics
14.LINQ
15.Network
16.Office
17.Reflection
18.Regular Expressions
19.Security
20.Services Event
21.Thread
22.Web Services
23.Windows
24.Windows Presentation Foundation
25.XML
26.XML LINQ
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
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.