using System;
namespace MyFirstProgram
{
class Program
{
static void Main(string[] args)
{
// This is the starting point of our program.
// It's where the program begins to run.
// The following lines of code display messages on the screen.
// We use the "Console.WriteLine" method to do this.
// This line says, "Print 'I like pizza!' on the screen."
Console.WriteLine("I like pizza!");
// This line says, "Print 'It's really good!' on the screen."
// Notice that we use double quotation marks to include the ' character.
Console.WriteLine("It's really good!");
// The program will stop running after these lines are executed.
}
}
}
using System;
namespace MyFirstProgram
{
class Program
{
static void Main(string[] args)
{
// The "Main" method is the starting point of our program.
// Console.Write("Hey!"); prints "Hey!" without moving to the next line.
Console.Write("Hey!");
// Console.WriteLine("Hello!"); prints "Hello!" and moves to the next line.
Console.WriteLine("Hello!");
// This is a single-line comment. Comments are ignored by the program and are used for explanations.
/*
* This is a multiline comment.
* You can write multiple lines of comments like this.
* It's useful for providing detailed explanations.
*/
// Console.WriteLine("Club of Developers"); prints "Club of Developers" and moves to the next line.
Console.WriteLine("Club of Developers");
// Console.ReadKey() waits for a key press before the program exits.
Console.ReadKey();
}
}
}
Code provides a basic introduction to C# programming concepts. Here's a brief explanation of the code for beginners:
using System;
namespace MyFirstProgram
{
class Program
{
static void Main(string[] args)
{
// Declaration of variables
int x; // This declares an integer variable named 'x'
// Initialization of variables
x = 123; // 'x' is assigned the value 123
// Declaration and initialization in one step
int y = 321; // This declares an integer variable 'y' and assigns it the value 321
// Performing arithmetic operations
int z = x + y; // 'z' is the result of adding 'x' and 'y'
// Different data types
int age = 21; // An integer variable to store a whole number
double height = 300.5; // A double variable to store a decimal number
bool alive = false; // A bool variable to store true or false
char symbol = '@'; // A char variable to store a single character
string name = "Bro"; // A string variable to store a series of characters
// Displaying information using Console.WriteLine
Console.WriteLine("Hello " + name); // Concatenating strings and variables
Console.WriteLine("Your age is " + age);
Console.WriteLine("Your height is " + height + "cm"); // Concatenating with a string
Console.WriteLine("Are you alive? " + alive);
Console.WriteLine("Your symbol is: " + symbol);
// Combining variables to create a new one
string userName = symbol + name; // Concatenating 'symbol' and 'name' to create a new string
Console.WriteLine("Your username is: " + userName);
// Waiting for user input to keep the console window open
Console.ReadKey();
}
}
}
Code demonstrates the usage of constants in C#. Here's a brief explanation of the code for beginners:
using System;
namespace MyFirstProgram
{
class Program
{
static void Main(string[] args)
{
// Constants are immutable values that are known at compile time and do not change during the program's execution.
const double pi = 3.14; // Declares a constant 'pi' with a value of 3.14
// Attempting to change a constant will result in a compilation error.
// Uncommenting the line below will result in an error:
// pi = 420; // You can't change the value of a constant
Console.WriteLine(pi); // Outputs the value of the 'pi' constant
// Waiting for user input to keep the console window open
Console.ReadKey();
}
}
}
Our code illustrates the concept of type casting in C#, where you convert values between different data types. Here's a brief explanation for beginners:
using System;
namespace MyFirstProgram
{
class Program
{
static void Main(string[] args)
{
// Type casting is the process of converting a value from one data type to another.
// This is useful when you need to work with different data types or convert user input.
double a = 3.14; // A double with the value 3.14
int b = Convert.ToInt32(a); // Convert the double 'a' to an integer 'b'
int c = 123; // An integer with the value 123
double d = Convert.ToDouble(c); // Convert the integer 'c' to a double 'd'
int e = 321; // An integer with the value 321
string f = Convert.ToString(e); // Convert the integer 'e' to a string 'f'
string g = "$"; // A string with the value "$"
char h = Convert.ToChar(g); // Convert the string 'g' to a character 'h'
string i = "true"; // A string with the value "true"
bool j = Convert.ToBoolean(i); // Convert the string 'i' to a boolean 'j'
// Display the data types of the converted variables
Console.WriteLine(b.GetType()); // Outputs the type of 'b'
Console.WriteLine(d.GetType()); // Outputs the type of 'd'
Console.WriteLine(f.GetType()); // Outputs the type of 'f'
Console.WriteLine(h.GetType()); // Outputs the type of 'h'
Console.WriteLine(j.GetType()); // Outputs the type of 'j'
// Waiting for user input to keep the console window open
Console.ReadKey();
}
}
}
Your code prompts the user to enter their name and age, then displays a greeting message along with their age. Here's a brief explanation of the code for beginners:
using System;
namespace MyFirstProgram
{
class Program
{
static void Main(string[] args)
{
// Prompt the user to enter their name and age
Console.WriteLine("What's your name?");
String name = Console.ReadLine(); // Read the user's name as a string
Console.WriteLine("What's your age?");
int age = Convert.ToInt32(Console.ReadLine()); // Read the user's age as a string and convert it to an integer
// Display a personalized greeting
Console.WriteLine("Hello " + name); // Greet the user by name
Console.WriteLine("You are " + age + " years old"); // Display the user's age
// Waiting for user input to keep the console window open
Console.ReadKey();
}
}
}
Below code demonstrates basic arithmetic operations and increment / decrement operations in C#. Here's a brief explanation for beginners:
using System;
namespace MyFirstProgram
{
class Program
{
static void Main(string[] args)
{
int friends = 5; // Declare and initialize a variable 'friends' with the value 5
friends = friends + 1; // Increment 'friends' by 1
// You can achieve the same result using these shortcuts:
// friends += 1; // Increment 'friends' by 1
// friends++; // Increment 'friends' by 1
// If you want to decrement the value, you can do:
// friends = friends - 1; // Decrement 'friends' by 1
// friends -= 1; // Decrement 'friends' by 1
// friends--; // Decrement 'friends' by 1
// You can perform other arithmetic operations in a similar way:
// friends = friends * 2; // Multiply 'friends' by 2
// friends *= 2; // Multiply 'friends' by 2
// friends = friends / 2; // Divide 'friends' by 2
// friends /= 2; // Divide 'friends' by 2
// You can also calculate the remainder of a division using the modulus operator '%':
// int remainder = friends % 2; // Calculate the remainder when 'friends' is divided by 2
Console.WriteLine(friends); // Output the value of 'friends'
// Waiting for user input to keep the console window open
Console.ReadKey();
}
}
}
Below code demonstrates the usage of various mathematical functions available in the Math class in C#. Here's a brief explanation for beginners
using System;
namespace MyFirstProgram
{
class Program
{
static void Main(string[] args)
{
// Declare and initialize two double variables
double x = 3;
double y = 5;
// Calculate the square of 'x' using Math.Pow
double a = Math.Pow(x, 2); // Result: 9.0
// Calculate the square root of 'x' using Math.Sqrt
double b = Math.Sqrt(x); // Result: 1.732...
// Calculate the absolute value of 'x' using Math.Abs
double c = Math.Abs(x); // Result: 3.0
// Round 'x' to the nearest integer using Math.Round
double d = Math.Round(x); // Result: 3.0
// Round 'x' up to the nearest integer using Math.Ceiling
double e = Math.Ceiling(x); // Result: 3.0
// Round 'x' down to the nearest integer using Math.Floor
double f = Math.Floor(x); // Result: 3.0
// Find the maximum value between 'x' and 'y' using Math.Max
double g = Math.Max(x, y); // Result: 5.0
// Find the minimum value between 'x' and 'y' using Math.Min
double h = Math.Min(x, y); // Result: 3.0
// Output the result of the calculations
Console.WriteLine(a); // Outputs 9.0
// Waiting for user input to keep the console window open
Console.ReadKey();
}
}
}
Below code uses the Random class to generate random numbers in C#. Here's a brief explanation for beginners:
using System;
namespace MyFirstProgram
{
class Program
{
static void Main(string[] args)
{
// Create an instance of the Random class to generate random numbers
Random random = new Random();
// Generate random integers between 1 and 6 (inclusive) for three variables
int num1 = random.Next(1, 7); // Result: Random number between 1 and 6
int num2 = random.Next(1, 7); // Result: Random number between 1 and 6
int num3 = random.Next(1, 7); // Result: Random number between 1 and 6
// Generate a random double between 0.0 (inclusive) and 1.0 (exclusive)
// double num = random.NextDouble();
// Output the generated random numbers
Console.WriteLine(num1);
Console.WriteLine(num2);
Console.WriteLine(num3);
// Waiting for user input to keep the console window open
Console.ReadKey();
}
}
}
Below code calculates the length of the hypotenuse of a right triangle using the Pythagorean theorem. Here's a brief explanation for beginners
using System;
namespace MyFirstProgram
{
class Program
{
static void Main(string[] args)
{
// Prompt the user to enter the lengths of sides A and B
Console.WriteLine("Enter side A: ");
double a = Convert.ToDouble(Console.ReadLine()); // Read side A as a double
Console.WriteLine("Enter side B: ");
double b = Convert.ToDouble(Console.ReadLine()); // Read side B as a double
// Calculate the length of the hypotenuse (side C) using the Pythagorean theorem
double c = Math.Sqrt((a * a) + (b * b)); // Calculate the square root of (a^2 + b^2)
// Display the calculated hypotenuse
Console.WriteLine("The hypotenuse is: " + c);
// Waiting for user input to keep the console window open
Console.ReadKey();
}
}
}
Our code demonstrates various string manipulation operations in C#. Here's a brief explanation for beginners:
using System;
namespace MyFirstProgram
{
class Program
{
static void Main(string[] args)
{
// Declare and initialize two strings
string fullName = "Bro Code";
string phoneNumber = "123-456-7890";
// Convert the string to uppercase
// fullName = fullName.ToUpper(); // Result: "BRO CODE"
// Convert the string to lowercase
// fullName = fullName.ToLower(); // Result: "bro code"
// Replace dashes in the phone number with empty strings
// phoneNumber = phoneNumber.Replace("-", ""); // Result: "1234567890"
// Insert "Mr." at the beginning of the full name
// string userName = fullName.Insert(0, "Mr."); // Result: "Mr. Bro Code"
// Get the length (number of characters) of the full name
// int fullNameLength = fullName.Length; // Result: 8
// Extract the first name and last name using substring
string firstName = fullName.Substring(0, 3); // Result: "Bro"
string lastName = fullName.Substring(4, 4); // Result: "Code"
// Output the results of string manipulation
Console.WriteLine(firstName); // Outputs "Bro"
Console.WriteLine(lastName); // Outputs "Code"
// Waiting for user input to keep the console window open
Console.ReadKey();
}
}
}
C# program that generates a random number guessing game:
using System;
namespace NumberGuessingGame
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Welcome to the Number Guessing Game!");
// Generate a random number between 1 and 100
Random random = new Random();
int randomNumber = random.Next(1, 101);
int attempts = 0;
bool guessedCorrectly = false;
while (!guessedCorrectly)
{
Console.Write("Guess the number (1-100): ");
int userGuess = int.Parse(Console.ReadLine());
attempts++;
if (userGuess == randomNumber)
{
guessedCorrectly = true;
Console.WriteLine($"Congratulations! You guessed the number {randomNumber} in {attempts} attempts.");
}
else if (userGuess < randomNumber)
{
Console.WriteLine("Try a higher number.");
}
else
{
Console.WriteLine("Try a lower number.");
}
}
Console.WriteLine("Thanks for playing!");
// Waiting for user input to keep the console window open
Console.ReadKey();
}
}
}
// In this program:
// The user is welcomed to the Number Guessing Game.
// A random number between 1 and 100 is generated.
// The program enters a loop where the user is asked to guess the number.
// The program provides feedback if the guessed number is too high or too low.
// Once the user guesses the correct number, the program congratulates them and shows the number of attempts.
// The program waits for user input to keep the console window open after the game is finished.
// It's a simple and engaging game that allows users to test their guessing skills.
Below provided C# code defines a simple program that demonstrates exception handling. Here's an explanation of how the code works:
namespace Program
{
public class Program
{
public static void Main()
{
try
{
// Prompt the user to enter an integer (for example, 5)
int index = Convert.ToInt32(Console.ReadLine()); // Input: 5
// Call BaseMethod with the provided index and display the result
Console.WriteLine(BaseMethod(index)); // Outputs the value from BaseMethod
}
catch (Exception ex)
{
// Handle any exceptions that occur
Console.WriteLine(ex.Message); // Output the exception message
Console.WriteLine(ex.StackTrace); // Output the stack trace for debugging
}
Console.ReadLine(); // Wait for user input before closing the console
}
public static int BaseMethod(int index)
{
// Call ChildMethod with the provided index
return ChildMethod(index);
}
public static int ChildMethod(int index)
{
// Define an integer array with values {1, 2, 3, 4, 5}
int[] arr = { 1, 2, 3, 4, 5 };
// Attempt to access an element in the array with the provided index
return arr[index];
}
}
}
// Input : 5
// Output :
Index was outside the bounds of the array.
at Program.Program.ChildMethod(Int32 index) in C:\Users\Vijay Sharma\source\repos\PracticeC#\PracticeC#\Program.cs:line 319
at Program.Program.BaseMethod(Int32 index) in C:\Users\Vijay Sharma\source\repos\PracticeC#\PracticeC#\Program.cs:line 314
at Program.Program.Main() in C:\Users\Vijay Sharma\source\repos\PracticeC#\PracticeC#\Program.cs:line 302
Here's an explanation of your C# code that lists and prints directories within a specified root path :
This C# program is designed to list and print the names of directories within a specified root path. Here's a brief explanation of what the program does:
using System; // Import the System namespace
using System.IO; // Import the necessary using directive for System.IO
namespace FileHandlingPractice
{
class Program
{
static void Main()
{
// Define the root directory path you want to work with
string rootPath = "D:\\FileHandlingPractice";
// Use Directory.EnumerateDirectories to retrieve a collection of directory paths
var directories = Directory.EnumerateDirectories(rootPath);
// Iterate through the collection of directory paths
foreach (var directory in directories)
{
// Print each directory path to the console
Console.WriteLine(directory);
}
}
}
}
// Output :
// D:\FileHandlingPractice\SubFolder1
// D:\FileHandlingPractice\SubFolder2
// Switch Statement
// Switch is an alternative to many "else if" statement !
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("What day is it today ?");
string? day = Console.ReadLine();
switch (day)
{
case "Monday":
Console.WriteLine("It's Monday !");
break;
case "Tuesday":
Console.WriteLine("It's Tuesday !");
break;
case "Wednesday":
Console.WriteLine("It's Wednesday !");
break;
case "Thursday":
Console.WriteLine("It's Thursday !");
break;
case "Friday":
Console.WriteLine("It's Friday !");
break;
case "Saturday":
Console.WriteLine("It's Saturday !");
break;
case "Sunday":
Console.WriteLine("It's Sunday !");
break;
default:
Console.WriteLine(day + " is not a day !");
break;
}
Console.ReadKey();
}
}
The hypatenuse squared is equals to the sum of sides square.
// Let's move into deep dive...
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Enter side a : ");
double a = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Enter side b : ");
double b = Convert.ToDouble(Console.ReadLine());
double c = Math.Sqrt((a * a) + (b * b));
Console.WriteLine("The hypotenuse is : " + c);
Console.ReadKey();
}
}
// Input 1 :
// Enter side a : 3
// Input 2 :
// Enter side b : 4
// Output :
// The hypotenuse is : 5
Let's move into deep dive...
// First we create the Program Class
class Program
{
public static void Main(string[] args)
{
// Create Object of Random class
Random random = new Random();
// Returns a non-negative random integer.
// A 32 - bit signed integer that is greater than or equal to 0 and less than "int.MaxValue".
int num1 = random.Next(); // Output : 1046318339
// The exclusive upper bound of the random number to be generated must be greater than or equal to 0.
// Return a 32-bit signed integer that is greater than or equal to 0, and less than maxValue.
// However, if maxValue equals 0, maxValue is returned.
int num2 = random.Next(7); // Output : 4
// Return a 32-bit signed integer that is greater than or equal to minValue and less than maxValue.
int num3 = random.Next(3,7); // Output : 6
Console.WriteLine(num1);
Console.WriteLine(num2);
Console.WriteLine(num3);
Console.ReadKey();
}
}
// Output :
1046318339
4
6
Let's move into deep dive...
// Replace(oldValue, newValue) method
// All occurance of "oldValue" replaced with the "newValue".
class Program
{
public static void Main(string[] args)
{
string fullName = "Club of Developers";
string phoneNumber = "123-456-7890";
string newPhoneNum = phoneNumber.Replace("-", "/");
Console.WriteLine(newPhoneNum);
Console.ReadKey();
}
}
// Output :
123/456/7890
// Substring(startIndex)
// Substring(startIndex, length)
class Program
{
public static void Main(string[] args)
{
string fullName = "Club of Developers";
string subStr1 = fullName.Substring(8); // Output : Developers
string subStr2 = fullName.Substring(8, 3); // Output : Dev
Console.WriteLine(subStr1);
Console.WriteLine(subStr2);
Console.ReadKey();
}
}
Let's move into deep dive...
// StartsWith(charValue)
// StartsWith(stringValue)
class Program
{
public static void Main(string[] args)
{
string fullName = "Club of Developers";
// Taking "char" as an argument
Console.WriteLine(fullName.StartsWith('C')); // True
Console.WriteLine(fullName.StartsWith('D')); // False
// Taking "string" as an argument
Console.WriteLine(fullName.StartsWith("Club")); // True
Console.ReadKey();
}
}
// Output :
Return true if the value matches beginning of the string, otherwise return false.
// ToLower()
class Program
{
public static void Main(string[] args)
{
string fullName = "Club of Developers";
Console.WriteLine(fullName.ToLower());
Console.ReadKey();
}
}
// Output :
Return a copy of the string which will be converted into lowercase.
// To access the underlying integer value associated with an enum item, you can explicitly convert it to an int.
// Example:
// Planets is an enum containing the names of celestial bodies, with associated integer values.
// To get the integer value of Planets.Mercury, you can do:
// int mercuryValue = (int)Planets.Mercury;
class Program
{
static void Main(string[] args)
{
//Console.WriteLine(Planets.Mercury + " is planet #" + (int)Planets.Mercury);
//Console.WriteLine(Planets.Pluto + " is planet #" + (int)Planets.Pluto);
String name = PlanetRadius.Earth.ToString();
int radius = (int)PlanetRadius.Earth;
double volume = Volume(PlanetRadius.Earth);
Console.WriteLine("planet: " + name);
Console.WriteLine("radius: " + radius + "km");
Console.WriteLine("volume: " + volume + "km^3");
Console.ReadKey();
}
public static double Volume(PlanetRadius radius)
{
double volume = (4.0 / 3.0) * Math.PI * Math.Pow((int)radius, 3);
return volume;
}
}
enum Planets
{
Mercury = 1,
Venus = 2,
Earth = 3,
Mars = 4,
Jupiter = 5,
Saturn = 6,
Uranus = 7,
Neptune = 8,
Pluto = 9
}
enum PlanetRadius
{
Mercury = 2439,
Venus = 6051,
Earth = 6371,
Mars = 3389,
Jupiter = 69911,
Saturn = 58232,
Uranus = 25362,
Neptune = 24622,
Pluto = 1188
}
// Output :
planet: Earth
radius: 6371km
volume: 1083206916845.7535km^3
The below code provided is a C# program that defines a list of strings and uses LINQ to filter out the strings that contain the substring "turorial". Here's my interpretation of the code:
So, the code above filters the stringList to include only the strings that contain the substring "turorial", and stores the filtered result in the result variable. In other words, the result variable will contain a list of all the strings in stringList that have the substring "turorial" in them.
Let's have an another example...
List colleagues = new List
{
new Colleague
{
Name = "Ankit Sir",
FavoriteQuote = "The best way to predict the future is to invent it.",
FavoriteFood = "Pizza",
Age = 25,
YearsOfExperience = 2
},
new Colleague
{
Name = "Paaji",
FavoriteFood = "Rajma Chawal",
Hobby = "Playing Cricket",
Age = 27,
YearsOfExperience = 2
},
new Colleague
{
Name = "Preeti Ma'am",
FavoriteMovie = "The Shawshank Redemption",
FavoriteAnimal = "Dogs",
Age = 23,
YearsOfExperience = 1
},
new Colleague
{
Name = "Karan Sir",
FavoriteQuote = "I don't always write code, but when I do, I prefer C#.",
Superpower = "Ability to code without any bugs",
Age = 22,
YearsOfExperience = 2
},
new Colleague
{
Name = "Manoj Sir",
FavoriteAnimal = "Pumba",
FunFact = "Able to eat anything like a pro",
Age = 24,
YearsOfExperience = 1
},
new Colleague
{
Name = "Sakshi",
Hobby = "Painting",
FavoriteMovie = "The Godfather",
Age = 26,
YearsOfExperience = 1
},
new Colleague
{
Name = "Minal",
FavoriteQuote = "Stay Hungry, Stay Foolish",
Superpower = "Invisibility",
Age = 23,
YearsOfExperience = 1
}
};
var result = colleagues.Where(s => s.Age >= 25 && s.YearsOfExperience >= 2);
The above code is using LINQ syntax to filter the colleagues list and select those colleagues who have YearsOfExperience equals to 1, and the filtered result is stored in the result variable.
The below code is using LINQ syntax to filter a collection of colleagues based on a specific condition, where the age of the colleague is between 23 and 26.
var filterResult = from item in colleagues
where IsTeeAger(item)
select item;
public static bool IsTeeAger(Colleague colleague)
{
return colleague.Age > 23 && colleague.Age < 26;
}
The below code demonstrates the usage of the OfType() method in LINQ to filter elements of a certain type from a mixed list. Here's what the code does:
public class Student
{
public int StudentId { get; set; }
public string StudentName { get; set; }
}
public static void Main()
{
IList mixedList = new ArrayList()
{
1,"One","Two",32.2,
new Student() { StudentId = 1,StudentName = "John"}
};
var stringResult = from std in mixedList.OfType()
select std;
}
0 Comments