Skip to content

Instantly share code, notes, and snippets.

@nikitas1010
Last active September 16, 2021 01:39
Show Gist options
  • Select an option

  • Save nikitas1010/77cba70085ace6931d092d578cbdc33f to your computer and use it in GitHub Desktop.

Select an option

Save nikitas1010/77cba70085ace6931d092d578cbdc33f to your computer and use it in GitHub Desktop.
OOP in c sharp
using System;
//using static System.Console;
using System.Collections.Generic;
public class MainClass
{
public static void Main(string[] args)
{
var shapes = new List<Shape> {
new Rectangle(),
new Triangle(),
new Circle()
};
foreach (var shape in shapes) {
//shape.Draw();
Shape shapeCast = (Shape)shape;
shapeCast.Draw();
Console.WriteLine(shapeCast.GetType());
}
var newShape = new Shape();
//var circleShape = (Circle)newShape;
//circleShape.Draw();
//Unhandled exception. System.InvalidCastException: Unable to cast object of type 'Shape' to type 'Circle'.
//at MainClass.Main(String[] args)
}
}
public class Shape
{
// A few example members
public int X
{
get;
private set;
}
public int Y
{
get;
private set;
}
public int Height
{
get;
set;
}
public int Width
{
get;
set;
}
// Virtual method
public virtual void Draw()
{
Console.WriteLine("Performing base class drawing tasks");
}
}
public class Circle : Shape
{
public override void Draw()
{
// Code to draw a circle...
Console.WriteLine("Drawing a circle");
}
}
public class Rectangle : Shape
{
public override void Draw()
{
// Code to draw a rectangle...
Console.WriteLine("Drawing a rectangle");
}
}
public class Triangle : Shape
{
public override void Draw()
{
// Code to draw a triangle...
Console.WriteLine("Drawing a triangle");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment