Welcome to Code Decipher. Are you passionate about programming and eager to master C#, ASP.NET, Visual Studo, Visual Studio code and web development? You’ve come to the right place! At Code Decipher, I provide step-by-step tutorials, practical coding examples, and engaging coding challenges to help you sharpen your skills and stay ahead in the fast-paced world of software development.
Master C# Unit Testing with xUnit – A Beginner’s Guide
Are you looking to improve your C# skills and write better, more reliable code? Unit testing is a game-changer, and in my latest YouTube video, I’ll walk you through how to use xUnit to write and run unit tests effectively in C#!
🔥 What You’ll Learn in This Video
✅ Setting up xUnit in your C# project
✅ Writing your first unit test
✅ Running and debugging tests
✅ Best practices for cleaner, more efficient tests
Whether you’re new to unit testing or just looking to refine your skills, this video is packed with valuable insights to help you level up your development game.
In this tutorial, I’ll show you different ways to install a NuGet package in Visual Studio 2022. NuGet is the package manager for .NET, and it’s essential for adding libraries and tools to your projects. Whether you’re a beginner or an experienced developer, this guide will walk you through the process step-by-step.
Installing NuGet packages is a common task in .NET development, and Visual Studio 2022 makes it incredibly easy. Below, I’ve embedded a YouTube video tutorial that demonstrates the entire process. Watch the video to see it in action, or follow the written steps below.
Different Ways to Install a NuGet Package in Visual Studio 2022:
Using the NuGet Package Manager:
Right-click on your project in the Solution Explorer.
Select Manage NuGet Packages.
Search for the package you want to install (e.g., Newtonsoft.Json).
Click Install.
Using the Package Manager Console:
Open the Package Manager Console from Tools > NuGet Package Manager > Package Manager Console.
Run the command: Install-Package PackageName (replace PackageName with the name of the package).
Using the .NET CLI:
Open a terminal or command prompt.
Navigate to your project directory.
Run the command: dotnet add package PackageName.
If you encounter any issues during the installation, feel free to leave a comment below, and I’ll be happy to help! Don’t forget to like, share, and subscribe to my YouTube channel for more programming tutorials.
Why Use NuGet? NuGet simplifies the process of adding third-party libraries to your .NET projects. It handles dependencies, updates, and versioning, making your development workflow more efficient. Whether you’re working on a small project or a large enterprise application, NuGet is a must-have tool.
Are you encountering the "git src refspec master does not match any, failed to push some refs" error while trying to push your commits to GitHub? Don’t worry! In this tutorial, I’ll walk you through the steps to fix this common Git error and get your code pushed successfully.
This error usually occurs when Git can’t find the branch you’re trying to push or when there are no commits to push. Watch the video tutorial above for a visual guide, or follow the steps below:
Steps to Fix the Error:
Verify your remote URL with git remote -v.
Create an initial commit if your branch is empty using git commit -m "Initial commit".
Push your branch to GitHub using git push origin branch-name.
Check if you’re on the correct branch using git branch.
For a more detailed explanation, watch the video tutorial embedded above. If you found this guide helpful, feel free to leave a comment below or share it with others who might benefit from it!
If you are unable to add controller to ASP.NET due to controller option being greyed out. Please check out my 1 minute youtube video which provides solution to this issue.
I've linked my YouTube video below, where I explain interface in C# with a practical example and a fun coding challenge at the end. Below the video, you'll find the actual code featured in the tutorial.
Try solving the coding challenge yourself before checking out the solution provided at the end of this blog - it’s a fantastic way to test your understanding and sharpen your skills! Happy coding! 😊
Actual code featured in the tutorial
using System;
using System.Collections.Generic;
namespace Interface_App
{
internal class Program
{
static void Main(string[] args)
{
List flyingThings = new List
{
new People(),
new Airplane()
};
foreach (var thing in flyingThings)
{
thing.Fly();
thing.Glide();
Console.WriteLine();
}
List speakingThings = new List
{
new People()
};
foreach (var thing in speakingThings)
{
thing.Speak();
Console.WriteLine();
}
}
}
interface IAirActivities
{
void Fly();
void Glide();
}
interface ISpeaking
{
void Speak();
}
public class People : IAirActivities, ISpeaking
{
public void Fly()
{
Console.WriteLine("People who fly airplanes are called pilot.");
}
public void Glide()
{
Console.WriteLine("People can glide in the air using gliders.");
}
public void Speak()
{
Console.WriteLine("People can speak at least one language.");
}
}
public class Airplane : IAirActivities
{
public void Fly()
{
Console.WriteLine("Airplanes are able to fly in the sky");
}
public void Glide()
{
Console.WriteLine("Airplanes can glide with their engines off");
}
}
}
Interface coding challenge solution
Below is the solution to the coding challenge featured in the video.
using System;
using System.Collections.Generic;
namespace InterfaceExcerciseApp
{
internal class Program
{
static void Main(string[] args)
{
IAnimal lion = new Lion();
IAnimal parrot = new Parrot();
IAnimal snake = new Snake();
List animals = new List { lion, parrot, snake};
foreach (IAnimal animal in animals)
{
Console.WriteLine(animal.Eat());
Console.WriteLine(animal.MakeSound());
Console.WriteLine();
}
}
}
public interface IAnimal
{
string Eat();
string MakeSound();
}
public class Lion : IAnimal
{
public string Eat()
{
return "Lions eat meat";
}
public string MakeSound()
{
return "Lion roars";
}
}
public class Parrot : IAnimal
{
public string Eat()
{
return "Parrots eat nuts.";
}
public string MakeSound()
{
return "Parrots sing";
}
}
public class Snake : IAnimal
{
public string Eat()
{
return "Snakes eat rodents.";
}
public string MakeSound()
{
return "Snakes hiss.";
}
}
}
I've linked my YouTube video below, where I explain method overloading in C# with a practical example and a fun coding challenge at the end. Below the video, you'll find the actual code featured in the tutorial.
Try solving the coding challenge yourself before checking out the solution provided at the end of this blog - it’s a fantastic way to test your understanding and sharpen your skills! Happy coding! 😊
Actual code featured in the tutorial
using System;
namespace MethodOverLoading
{
internal class Program
{
static void Main(string[] args)
{
Log log = new Log();
log.DisplayLog("Welcome to this program.");
log.DisplayLog("You have successfully created the file on ", DateTime.Now);
log.DisplayLog("Requires user authentication", 401);
}
}
public class Log
{
public void DisplayLog(string message)
{
Console.WriteLine(message);
}
public void DisplayLog(string message, DateTime dateAndTime)
{
Console.WriteLine($"{message}, {dateAndTime}");
}
public void DisplayLog(string error, int errorCode)
{
Console.WriteLine($"{error}, error code: {errorCode}");
}
}
}
Method Overloading coding challenge solution
Below is the solution to the coding challenge featured in the video. In this example, I’ve used the double data type for the square and rectangle area parameters, and int for the circle area. However, feel free to use any data types you prefer—as long as the method signatures are different, your solution will work perfectly for this challenge.
using System;
namespace MethodOverLoadingExcercise
{
internal class Program
{
static void Main(string[] args)
{
Area(3.0);
Area(1.5, 4);
Area(4);
}
//area of a square
public static double Area(double length)
{
//if decimal, then round to 2 decimal places
double output = Math.Round(length * length, 2);
Console.WriteLine($"Area of square: {output}");
return output;
}
//area of a rectangle
public static double Area(double length1, double length2)
{
double output = Math.Round(length1 * length2, 2);
Console.WriteLine($"Area of rectangle: {output}");
return output;
}
/* area of a circle
We use an integer parameter for the radius to make this
method's signature unique compared to the square's area method.
This is important because both shapes involve a single numeric input.
*/
public static double Area(int radius)
{
//const means variable is a constant
const double pi = Math.PI;
//Area of a circle = pi * r * r, rounded to 2 decimals
double output = Math.Round(pi * radius * radius, 2);
Console.WriteLine($"Area of circle: {output}");
return output;
}
}
}
I've linked my YouTube video below, where I explain method overriding in C# with a practical example and a fun coding challenge at the end. Below the video, you'll find the actual code featured in the tutorial.
I have used virtual method in the example so i have used abstract class and method for the coding challenge solution. You can solve using both ways. Try solving the coding challenge yourself before checking out the solution provided at the end of this blog - it’s a fantastic way to test your understanding and sharpen your skills! Happy coding! 😊
Actual code featured in the youtube tutorial above
using System;
namespace Method_Overriding
{
internal class Program
{
static void Main(string[] args)
{
Engineer engineer = new Engineer();
engineer.Work();
FrontEndEngineer frontEnd = new FrontEndEngineer();
frontEnd.Work();
BackEndEngineer backEnd = new BackEndEngineer();
backEnd.Work();
DevOpsEngineer devOps = new DevOpsEngineer();
devOps.Work();
}
}
public class Engineer //Parent class, base class, superclass
{
public virtual void Work()
{
Console.WriteLine("All engineers need to work");
}
}
public class FrontEndEngineer : Engineer //Child class, derived class
{
public override void Work()
{
Console.WriteLine("Front end engineers creates the user interface of website and application");
}
}
public class BackEndEngineer : Engineer
{
public override void Work()
{
Console.WriteLine("Back end engineers creates and maintains the serverside of application");
}
}
public class DevOpsEngineer : Engineer
{
public override void Work()
{
Console.WriteLine("Dev ops engineers maintains the companies software operation");
}
}
}
Method Overriding Coding Challenge Solution
using System;
namespace MethodOverridingExcerciseDemo
{
internal class Program
{
static void Main(string[] args)
{
Remote TV = new Tv();
TV.PressPlay();
Remote MusicPlayer = new MusicPlayer();
MusicPlayer.PressPlay();
Remote VideoGameConsole = new VideoGameConsole();
VideoGameConsole.PressPlay();
}
}
//Remote considered as abstract and it will be our parent class
public abstract class Remote
{
public abstract void PressPlay(); //abstract method has no body
}
public class Tv : Remote
{
public override void PressPlay()
{
Console.WriteLine("Starting a movie.");
}
}
public class MusicPlayer : Remote
{
public override void PressPlay()
{
Console.WriteLine("Starting a song");
}
}
public class VideoGameConsole : Remote
{
public override void PressPlay()
{
Console.WriteLine("Starting a game");
}
}
}
In C# class is a blueprint for creating objects. It contains data (properties) and behaviour (methods). We can build multiple objects with distinct properties and methods using classes without having to repeat the code.
Class Syntax: Creating a generic C# Class
public class Car //car is the class name and Pascal case
{
public string Model { get; set; } //properties
public string Color { get; set; }
public void Start() //method
{
Console.WriteLine("Car started.");
}
public void Stop() //method
{
Console.WriteLine("Car stopped.");
}
}
A generic class in C# is created using a class keyword followed by class name. Class name, property name, method name must always be Pascal case i.e. Starting letter must be capital case. Class can have different properties and methods. We cannot use the class directly without creating an object. In order to use class we must create an object which is an instance of class.
Creating an object
Once class is created. Object can be creating by instantiating a class with the new keyword. Attributes can be initialized using the dot operator followed by attribute name as shown below.
Car myCar = new Car();
myCar.Model = "Toyota Camry";
myCar.Color = "Red";
myCar.Start();
We can also create an object and initialize attributes directly using { }
Car myCar = new Car
{
Model = "Toyota Camry",
Color = "Red"
};
Creating object using constructor
We can also create an object and initialize attributes directly using constructor. Constructor name must be same as class name. Arguments are passed in to the constructor. this keyword is used to link arguments to attributes.
public class Car
{
public string Model { get; set; }
public string Color { get; set; }
public Car(string model, string color) //Constructor
{
this.Model = model;
this.Color = color;
}
public void Start()
{
Console.WriteLine("Car started.");
}
public void Stop()
{
Console.WriteLine("Car stopped.");
}
}
Once the constructor is set in a class we can now create an object by directly passing in values to the constructor.
Car myCar = new Car("Mercedes", "blue");
Console.WriteLine(myCar.Model); //outputs Mercedes
Console.WriteLine(myCar.Color); //outputs blue
Types of classes
Regular Classes
Abstract Classes
Static Classes
Partial Classses
Regular Class: Needs to be instantiated to create objects. These are the most common type. Examples shown above so far are regular classes.
Abstract Class: Abstract classes are something that exists as generic idea but does not physically exist. For e.g. vehicle can be anything a bike, truck, car, lorry, boat etc. Abstract classes cannot be instantiated directly. They serve as a base class for other classes, providing a common interface. Abstract class can have its own properties and methods. All derived classes must provide their own implementation for these properties and methods. Abstract class is created using abstract keyword.
public abstract class Vehicle
{
//Abstract properties and methods (no implementation)
public abstract string Model { get; set; }
public abstract string Color { get; set; }
public abstract void Start();
public abstract void Stop();
}
Once public class is created. We can use this public class as a base class as follows. Each abstract properties and methods must be implemented during this phase.
public class Car : Vehicle
{
//implementing abstract properties
public override string Model { get; set; }
public override string Color { get; set; }
//constructor
public Car(string model, string color)
{
Model = model; //can also write this.Model
Color = color; //can also write this.Color
}
//implementing abstract method
public override void Start()
{
Console.WriteLine($"{Model} car started.");
}
public override void Stop()
{
Console.WriteLine($"{Model} car stopped.");
}
}
public class Truck : Vehicle
{
//implementing abstract properties
public override string Model { get; set; }
public override string Color { get; set; }
//constructor
public Truck(string model, string color)
{
Model = model; //can also write this.Model
Color = color; //can also write this.Color
}
//implementing abstract method
public override void Start()
{
Console.WriteLine($"{Model} truck started.");
}
public override void Stop()
{
Console.WriteLine($"{Model} truck stopped.");
}
}
Once the abstract class is created and implemented on its derived class then we can use it by creating objects from the derived class.
internal class Program
{
static void Main(string[] args)
{
Car myCar = new Car("BMW", "red"); //Car is the derived class
myCar.Start(); //BMW car started.
myCar.Stop(); //BMW car stopped.
Truck myTruck = new Truck("Tesla", "silver");
myTruck.Start(); // Tesla truck started.
myTruck.Stop(); //Tesla truck stopped.
}
}
Static Class: Static class cannot be instantiated and can be used directly. All members of a static class must be static. An example is shown below
public static class CarUtilities
{
public static void displayInformation(Car car)
{
Console.WriteLine($"Model: {car.Model}");
Console.WriteLine($"Color: {car.Color}");
}
}
Partial Class:Partial class can be defined across multiple files. This is useful for splitting large class definitions into smaller, more manageable parts.
I have also created a youtube video about this topic please feel free to check it out. Happy coding.