All Articles

Stack Vs Heap

Stack and Heap refers to 2 distinct memory areas utilized by an executing program based on the data type of data that it deals at a point during its execution. Stack is that part of memory that a program uses to keep track of its execution flow. For example it stores the currently executed method…

All Articles

What is the purpose of static modifier?

Static modifier is commonly used in all programming languages. There are two distinct reasons for using the static modifier whether its C, Java, C#, PHP or Ruby – To access the class members without instantiating the object. eg: public class CutGrass{ public static void CleanMower(){ } } var endTheJob = CutGrass.CleanMower(); 2. To restrict the representation…

All Articles

Arrays Vs Lists – Which one to use?

Both Arrays and Lists helps us to store list of elements. But which one to choose is an important design decision that is directly related to application performance. Arrays are strongly typed – meaning they can only store data of one type. Use Arrays where the size and type of elements is fixed and we…

All Articles

C# File, Directory Manipulation

C# provide two versions of File, Directory manipulation options – 1) Static methods based and 2) Instance methods based. Static method based operations are provided by the File and Directory classes both derived from System.IO class. Instance method based operations are provided by the FileInfo and DirectoryInfo classes again both derived from System.IO class. File…

All Articles

MVC Architecture

MVC architecture has been in place since past 4 decades or so when GUI (Graphical Use Interfaces) started to be used widely. The idea is simple – to implement separation of concerns.  Plainly put, to separate 1) presentation (UI) 2) user interactions and 3) underlying data and logic/behavior. It might be easy to build a web…

All Articles

C# Program to find Age

Below is a C# program to find Age from a Date of Birth. Enjoy! public class Person    {        public string Name { get; set; }        public Person(DateTime birthdate)        {            BirthDate = birthdate;        }        public DateTime BirthDate { get; private set; }        public int Age{                        get {                 var timeSpan = DateTime.Today – BirthDate;                var years = timeSpan.Days / 365;                return years;                                        }        }    }    public class Program    {        public static void Main(string[] argvs)        {            var person = new Person(new DateTime(1998,2,14));                        Console.WriteLine(person.Age);        }    }

All Articles

Usage of params modifier in C#

Lets see how to use params modifier in C#. The perfect example is Calculator implementation. ‘params’ access modifier when used on a method argument, allows it to accept multiple argument values. Lets see the simple Calculator implementation below. As you can see, method argument ‘numbers’ is defined as integer array and being called out by…

All Articles

Constructor overloading in C#

Constructors need to be overloaded depending on what extend of data/properties need to be initialized in order to set the object to a particular state. Below a good example using a Customer / Orders example. Note that Customer constructor is overloaded in 3 different ways based on what data need to be initialized. Here we…

All Articles

Using LINQ in C#

LINQ or Language Integrated Query gives the capability to query objects and C# allows two distinctive ways to achieve this – You can either use LINQ query operators model or LINQ extension methods model with Lamba expressions on Func<> delegate. We have –  LINQ to Objects – Objects in memory eg: Collections ·       LINQ to Entities…

All Articles

Using DateTime in C#

Below is very simple usage of DateTime – class DateTimePr     {         static void Main(string[] args)         {             var datetime = new DateTime();             var now = DateTime.Now;             var today = DateTime.Today;             Console.WriteLine(now);             Console.WriteLine(today);             Console.WriteLine(now.Hour);             Console.WriteLine(now.ToLongDateString());             Console.WriteLine(now.ToString());         }     }

All Articles

Reading a file in C#

Below is a simple program in C# that reads a file and outputs the longest word in it. Enjoy! using System; using System.IO; using System.Collections.Generic; namespace <yourNS> {     class FilesNDirs     {         public static void Main(string[] argvs)         {             var path = @”C:\Users\deepesh\Desktop\Test\test.txt”;             var textFile = File.ReadAllText(path);             var words = textFile.Split(‘ ‘);             var wordlenpt = new string[100];             var wordlenarr = new List<int>();             foreach (var i in words)             {                 if (i.Length > 0)                 {                     wordlenarr.Add(i.Length);                     wordlenpt[i.Length] = i;                     Console.WriteLine(i);                 }             }             wordlenarr.Sort();             foreach (var i in wordlenarr)             {                 Console.WriteLine(i);             }             Console.WriteLine(“\n\nLargest word in the file is >>” +  wordlenpt[wordlenarr[wordlenarr.Count – 1]]);         }     } }

All Articles

Finding Lowest number from a List in C#

Below is a simple program to find the lowest number from a list of numbers – using System; using System.Collections.Generic; namespace GroundCSApp {     class GetSmallest     {         public static void Main(string[] argvs)         {             var numlist = new List<int> { 1, 2, 3, 4, 5, 6 };             var finallst = GetSmallests(numlist, 3);             foreach (var i in finallst)             {                 Console.WriteLine(i);             }         }         public static List<int> GetSmallests(List<int> lst, int cnt)         {             if (cnt > lst.Count)             {                 throw new ArgumentOutOfRangeException(“cnt”, “Count of numbers is  greater than the list count”);             }             var buff = lst;             var smalllst = new List<int>();             while (buff.Count > cnt)             {                 var min = GetiSmallest(buff);                 smalllst.Add(min);                 buff.Remove(min);             }             return smalllst;         }         public static int GetiSmallest(List<int> lsti)         {             var min = lsti[0];             for (var j = 1; j < lsti.Count; j++)             {                 if (lsti[j] < min)                 {…

All Articles

Simple C# Programs

Here is some basic, simple, handy C# programs for you to enjoy and refresh your memory – using GroundCSApp; using System; using System.Collections.Generic; using System.Linq; namespace GroundCSApp {     public enum ShippingMethod     {         Regular = 1,         Priority = 2,         Snail = 3     }     class Program     {         static void Main(string[] args)         {             //——————————————————-             //non -primitive/reference type eg: number              //array creation and assignment                          var numbers = new int[3];             numbers[0] = 23;             var numbers2 = numbers;             numbers[0] = 24;             Console.WriteLine(“Value of variable numbers is changed  and it is >>” + numbers[0]);             //——————————————————–             //——————————————————–             //non-primitive, immutable, string array creation assignment             var names = new string[3] { “John”, “Luke”, “Mark” };             //String Join example             var joinedName = string.Join(“,”, names);             Console.WriteLine(“\n\n” + joinedName);             var strArray = new string[] { “Text”, “Book”, “Light” };             var strArray2 = strArray;             //example for reference type where             //original value is modified             strArray2[0] = “Candle”;…

All Articles

Code Reuse via Composition in C#

Composition is a common object oriented concept that enables us to implement loose coupling as well as code-reuse. Lot of times we recommend our developers to use more composition and less inheritance due this very fact. Inheritance supports code-reuse, but makes application tightly coupled and creates long inheritance hierarchies that creates inter-dependencies. Inheritance implements a…

All Articles

Constructor Inheritance in C#

Like any other Object Oriented Programming language, C# does not allow parent constructor to be automatically inherited. It need to explicitly defined in the derived class. Below is an example to explain this – Below is the parent class – namespace ConstructorInh {     public class Fruit     {         private readonly string _color;         public Fruit(string color)         {             _color = color;             Console.WriteLine(“I am a Fruit with Color {0}”, _color);         }     } } Below is the…

All Articles

Dynamic Typing in C#

Well, C# provides this option to prove that it is flexible. If you are too fond of dynamic typing, use scripting languages such as PHP! Below is an example of how to use it – you will see that program will compile without errors and will display two different values for a as intended –…

All Articles

C# Generics

C# Generics are really useful when we want to reuse a class for different types and with constraints on what those types would be without rewriting those classes. C# allows at least 5 different kinds of Generics usage as related to the kind of constraints that we can use plus the most basic implementations such…

All Articles

C# Indexers

C# Indexers is a simple implementation of key/value pairs using Dictionary type. Below is a sample implementation of a telephone directory –TelephoneDirectory class using System.Collections.Generic; namespace Indexers {     public class TelephoneDirectory     {         private readonly Dictionary<string, string> _dictionary = new Dictionary<string, string>();         public string this[string key]         {             get { return _dictionary[key]; }             set { _dictionary[key] = value; }         }     } } As seen above, we use the ‘this[]’ notation to create the public property that sets/returns indexed value. We…

All Articles

C# Inheritance

We generally apply the concept of inheritance to implement a IS-A relationship. For example to implement a relationship that says an Apple is a Fruit or Earth is a cosmic object. We use inheritance very carefully so that it does not lead to long complex/un-maintainable object hierarchies, but to implement very specific object hierarchies with…

All Articles

C# Interfaces and how to implement loose coupling by Dependency (specific implementation of interface) injected via constructor overloading

Interface is a similar language construct such as class, but fundamentally different from a class. Some people claim that Interface is a way to implement multiple inheritance – this claim is also not true! If we were to implement inheritance via interfaces, then we would have re-used, but there is no code reuse while implementing…

All Articles

C# Abstract Classes Vs Interfaces

We use abstract classes when the base class can’t have concrete implementation and that we need the derived class to fully implement it. If at least one of the member is abstract, then the class will need to be declared as abstract. If a class derives an abstract class, then it needs to override all…

All Articles

Simple Stop Watch implementation in C#

Below is a simple stop watch implemented in C#, enjoy!StopWatch using System; namespace StopWatchApp {     public class StopWatch     {         public DateTime StarTime { get; set; }         public DateTime StopTime { get; set; }         public string ClockState { get; set; }         public void StartClock()         {             if(this.ClockState == “started”)                 throw new InvalidOperationException(“Invalid Operation”);             this.StarTime = DateTime.Now;             this.ClockState = “started”;         }         public void StopClock()         {             this.StopTime = DateTime.Now;             this.ClockState = “stopped”;         }         public TimeSpan ElapsedTime()         {             return this.StopTime – this.StarTime;         }     }  } Main Program using System; namespace StopWatchApp {     public class Program     {         public static void Main(string[] args)         {             Console.WriteLine(“Enter Start to Start the Clock,  Enter Stop to Stop the Clock to see the elapsed time.  Enter Quit to exit.”);             var clock = new StopWatch();             int alreadystarted = 0;             while (true)             {                 var inp = Console.ReadLine();                                 if (inp != “Quit”)                 {…

All Articles

Simple Workflow Engine Implementation in C#

Below is a simple implementation of work flow engine using interfaces and the concept of injecting overloaded class implementations via the dependent class method. The class constructor creates the List for storing the specific workflow implementations which are further executed.Interface – IWorkFlowActivities namespace WFEngine {     public interface IWorkFlowActivities     {         void Execute();     } } CarWorkflow using System; namespace WFEngine {     public class CarWorkflow : IWorkFlowActivities     {         public void Execute()…

Code First
All Articles

Using Code First first

Traditional ways of software development focus on DB-first implementation methodology. But we are in the realm of latest developments and ORM models has taken us to a level that is was a complex ordeal some years back. Eventhough a thorough domain/ERD based approach provides some advantages, there are far more overall improvements to development and…

All Articles

Using Extension Methods in C#

Extension methods are a way to add methods to a class without changing its source code or adding it into a derived class. Creating extension methods example Define extension method – public static class StringExtensions     {         public static string Reduce(this String str, int numOfWords)         {             if (numOfWords <= 0)                 return str;             var numWords = str.Split(‘ ‘);             if (numOfWords >= numWords.Length)                 return str;             return String.Join(” “, numWords.Take(numOfWords));         }     } Shorten is an extension class on the String class. Adding as above, we were able…

All Articles

C# Events and Delegates

We use events and delegates to extend applications and to implement loose coupling. Rather than adding various method calls within an implementation and then recompiling the class, we publish the need to call a set of methods as an event from the class that will invoke those methods (publisher). The publisher will thus define the delegate which will act…

All Articles

Using C# Delegates

  Delegates is a way to support addition of multiple features (eg: methods) to a framework without the need to recompile the core class that uses these methods. Delegate is a reference to a function/s and is itself an object (derived from MulticastDelegate) that knows how to call a method or group of methods. The…

All Articles

Preferred Multithreading in C# ASP.NET

Parallel execution has been one of the core techniques of programming languages that enables and stabilizes the heavy orchestrated flow of information across information management systems. All Object Oriented Programming languages provides couple different ways to implement this to function smoothly under heavy and stressful load 🙂 A better way was introduced in C# which…

All Articles

C# Lambda expressions

Lambda expressions are anonymous methods that does not have access modifiers, name or a return. They are used for convenience (less code) and makes code more readable. Lambda expression takes the form below – arg => expression //spelled as argument goes to expression This can be used in 3 distinct ways as below – ()…