Browsing articles tagged with " useful"
Oct
20

A D’oh Moment

I know this is something that most devs will not find interesting but it really made me smile when I stumbeld across using static members to count object instances. Like I’ve said I’m a noob and have jumped between technolgies so I decided this week to focus on learning the C# 3.5 Language from the ground up. I dug out my copy of Step by Step C# 2008 and decided to do a Chapter every time I needed a 5 min break from my Drudge (Smokers can have a Cigarette, why can’t coders have Dev Breaks??). After running though the variables, DataTypes etc I came across the classes and methods sections then got to the statics Which had the following little sample which I found very enlightening and though I’d share. It will also be for personal ref later.
using System;

namespace TheBasics
{
public class Circle
{
private int _radius;

public static int numCircles = 0;

public Circle()
{
_radius = 0;
numCircles++;
}

public Circle(int initialRadius)
{
_radius = initialRadius;
numCircles++;
}

public double Area()
{
return Math.PI*_radius*_radius;
}
}
}

So basically what this would allow you to do is Call the Static value numCircles which would have a count of all instances of the Circle Class. Simple I know bu t I liked it
Circle circle1 = new Circle();
Circle circle2 = new Circle();
Console.WriteLine("There are {0}, Circle objects",Circle.numCircles);

On A side note whilst creating This post I was struggeling to put nicley coloured and formatted code into the post. I found this and It worked a treat

Digital Infamy

The home of Designer/Developer and all round web geek Andrew Allison. The site is basically my playground and will hopefully house my thoughts and some of my work. At the minute I'm still just playing with it to see what feels right.