This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.
Let us find out the top 5 differences between class variables and local variables based on their functionality and usage and summarize with examples.
How to use virtual override new keywords in C#
In this article, let's explore the different keywords present in C# to implement method overriding with illustrating examples.
Understanding Polymorphism in OOP made Easy
In this detailed article, let's understand what is Polymorphism, types, features and how it works with illustrating examples in C#
Understanding Inheritance in OOP made Easy
In this detailed article, let's explore the concept of Inheritance in Object Oriented Programming with illustrating examples
Understanding Abstraction in OOP made Easy
In this detailed article, let's explore what is abstraction in OOP with an illustrated example and understand how it works
Understanding Encapsulation in OOP made Easy
In this article, let's understand the basics of encapsulation and why this is an important characteristic of any Object Oriented Language
Garbage Collection in ASP.NET Core Simplified
In this article, let's look at how Garbage Collection works and things we need to keep in mind while developing memory optimized applications in dotne..
How is LINQ executed in EF Core Simplified
In this article, let's look at the two main concepts in LINQ execution patterns that help in writing efficient and memory conscious expressions.
How can you restrict the number of instances that can be created on a class?
- To keep a track on the number of instances created on a class, you can maintain a static counter that is incremented each time the constructor is called. By principle, the constructor is called exactly once whenever a new instance is created.
- If the counter reaches over a limit, you can throw an Exception which breaks the instantiation.
class MyClass2
{
private static int _counter = 0;
public MyClass2()
{
if (_counter > 2)
{
throw new Exception("Instances created beyond limit");
}
else
{
++_counter;
}
}
public void ShowCounter()
{
Console.WriteLine($"Counter is at {_counter}");
}
}
MyClass2 c;
for (int i = 0; i < 5; i++)
{
c = new MyClass2();
c.ShowCounter();
}
output:
Counter is at 1
Counter is at 2
Counter is at 3
Unhandled exception. System.Exception: Instances created beyond limit