Do you want to learn PYTHON?
A constructor is a special method of the class which gets automatically invoked whenever an instance of the class is created. Like methods, a constructor also contains the collection of instructions that are executed at the time of Object creation. It is used to assign initial values to the data members of the same class.
For example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConstructorDestructor
{
internal class Program
{
static void Main(string[] args)
{
numbers num = new numbers();
numbers numP = new numbers("Parameterized");
}
}
public class numbers
{
public numbers()
{
Console.WriteLine("I am the constructor class.");
}
public numbers(string name)
{
Console.WriteLine("I am the " + name + "constructor");
}
}
}
Destructors in C# are methods inside the class used to destroy instances of that class when they are no longer needed. The Destructor is called implicitly by the .NET Framework’s Garbage collector and therefore programmer has no control as when to invoke the destructor. An instance variable or an object is eligible for destruction when it is no longer reachable.
For example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConstructorDestructor
{
internal class Program
{
static void Main(string[] args)
{
numbers num = new numbers();
}
}
public class numbers
{
public numbers()
{
Console.WriteLine("I am the constructor class.");
}
~numbers()
{
Console.WriteLine("Destructor called. Program finished.");
}
}
}
In C#, an abstract class is a class that cannot be instantiated. Instead, it serves as a base class for other classes to inherit from. Abstract classes are used to define a common set of behaviors or properties that derived classes should have.
For example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
namespace Abstraction
{
public abstract class father
{
public abstract void car();
public abstract void shop();
public void nonAbstract()
{
Console.WriteLine("Non Abstract method can be there");
}
}
public class son1 : father
{
public override void car()
{
Console.WriteLine("Car of son1");
}
public override void shop()
{
Console.WriteLine("Shop of son1");
}
}
public class son2 : father
{
public override void car()
{
Console.WriteLine("Car of son2");
}
public override void shop()
{
Console.WriteLine("Shop of son2");
}
}
internal class Program
{
static void Main(string[] args)
{
son1 s1 = new son1();
s1.car();
s1.shop();
son2 s2 = new son2();
s2.car();
s2.shop();
}
}
}
Another way to achieve abstraction in C#, is with interfaces.
An interface is a completely "abstract class", which can only contain abstract methods and properties (with empty bodies)
For example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Interface
{
interface IFather
{
void number();
void name();
}
public class son : IFather
{
public void number()
{
Console.WriteLine("Number from son class.");
}
public void name()
{
Console.WriteLine("Name from son class.");
}
}
internal class Program
{
static void Main(string[] args)
{
son s = new son();
s.number();
s.name();
}
}
}
Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism that binds together code and the data it manipulates. In a different way, encapsulation is a protective shield that prevents the data from being accessed by the code outside this shield.
Technically in encapsulation, the variables or data of a class are hidden from any other class and can be accessed only through any member function of its own class in which they are declared.
As in encapsulation, the data in a class is hidden from other classes, so it is also known as data-hiding.
Encapsulation can be achieved by: Declaring all the variables in the class as private and using C# Properties in the class to set and get the values of variables.
For example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Encapsulation
{
internal class Program
{
static void Main(string[] args)
{
driverCode dc = new driverCode();
dc.num = 123;
dc.nam = "Fuad";
dc.em = "201030@iubat.edu";
Console.WriteLine(dc.num);
Console.WriteLine(dc.nam);
Console.WriteLine(dc.em);
}
}
public class driverCode
{
private int number;
private string name;
private string email;
public int num
{
get { return number; }
set { number = value; }
}
public string nam
{
get { return name; }
set { name = value; }
}
public string em
{
get { return email; }
set { email = value; }
}
}
}
Function overloading is a feature of object-oriented programming that allows you to create multiple functions with the same name but different parameters. This way, you can use the same function name for different tasks, depending on the types and number of arguments you pass to it.
For example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FunctionOverLoadding
{
internal class Program
{
static void Main(string[] args)
{
driver d = new driver();
d.function1();
d.function2(2);
//string name = d.function2();
//Console.WriteLine(name);
}
}
public class driver
{
public void function1()
{
Console.WriteLine("I am function - 1");
}
public void function2(int num)
{
Console.WriteLine("I am function - " + num);
}
//public string function2()
//{
// return "Fuad";
//}
}
}
Function overriding is a technique that allows you to provide a new implementation of a method inherited from a base class in a derived class. You can use the override modifier to indicate that you are overriding a virtual or abstract method from the base class. The override method must have the same signature as the overridden base method, but it can have a different return type if it is more derived than the base type. This way, you can change the behavior of the method in the derived class, which overrides the method in the base class. It enables polymorphism, which allows you to treat objects of different classes in a consistent way when they are accessed through a pointer or reference to a common base class.
For example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace FunctionOverriding
{
internal class Program
{
static void Main(string[] args)
{
father f = new father();
f.car();
son s = new son();
s.car();
}
}
public class father
{
public virtual void car()
{
Console.WriteLine("I am from father class.");
}
}
public class son : father
{
public override void car()
{
Console.WriteLine("I am from son class.");
}
}
}
An indexer is a special property that allows you to access a class or a struct as an array. It lets you use the square brackets ([ ]) to get or set the values of a member variable of the class or struct.
For Example:
using System;
namespace Indexer
{
internal class Program
{
static void Main(string[] args)
{
oddNumbers odd = new oddNumbers();
odd[0] = 10;
odd[1] = 20;
odd[2] = 30;
for(int i = 0; i < 3; i++)
{
Console.WriteLine(odd[i]);
}
}
}
public class oddNumbers
{
private int[] nums = new int[3];
public int this [int i]
{
get
{
return nums[i];
}
set
{
nums[i] = value;
}
}
}
}
In C#, exception handling is a programming construct that allows developers to gracefully handle runtime errors and exceptions that may occur during the execution of a program. It helps prevent abrupt program termination and provides a structured way to deal with errors.
One crucial aspect of C# exception handling is the finally block. The finally block is used in conjunction with the try and catch blocks to ensure that certain code is executed regardless of whether an exception is thrown or not.
Here's how it works:
try Block: The try block is used to enclose the code that might raise an exception. If an exception occurs within this block, the control is transferred to the corresponding catch block.
catch Block: The catch block follows the try block and is used to handle the exception that was thrown. It contains code that specifies how to respond to the specific exception type. You can have multiple catch blocks to handle different types of exceptions.
finally Block: The finally block, which comes after the catch block(s), contains code that will be executed regardless of whether an exception was thrown or not. It's often used for cleanup tasks, such as closing files or releasing resources.
The finally block ensures that cleanup code is executed no matter what happens in the try block, whether an exception occurs or not. This helps maintain the integrity of the program's state and resources, even in the presence of exceptions.
using System;
using System.CodeDom;
namespace tryCatch
{
internal class Program {
static void Main(string[] args)
{
int[] nums = { 1, 2, 3, 4, 5 };
for(int i = 0; i < 5; i++)
{
Console.WriteLine(nums[i]);
}
try
{
Console.WriteLine(nums[5]);
}
catch(IndexOutOfRangeException ex)
{
Console.WriteLine(ex.Message);
//Console.WriteLine(ex);
}
//catch(Exception ex)
//{
// Console.WriteLine(ex.ToString());
//}
finally
{
Console.WriteLine("I will always be there.");
}
}
}
}
A generic class is a class that can work with any data type. You can create a generic class by using a type parameter inside angle brackets, like this: class MyClass<T> { ... }. The type parameter T can be replaced by any type when you create an instance of the class. For example, MyClass<int> or MyClass<string>. This way, you can reuse the same class for different types of data without writing duplicate code123.
Generic classes are useful for creating collections, such as lists, stacks, queues, etc., that can store any type of data4. They also help you write more type-safe and maintainable code.
For Example:
using GenericClass;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GenericClass
{
internal class Program
{
static void Main(string[] args)
{
Cwr<string> cwr = new Cwr<string>() { price = "1500", courseName = "Python Private Batch - 7", description = "Wow" };
Console.WriteLine(cwr);
Console.WriteLine(cwr.price);
Console.WriteLine(cwr.courseName);
Console.WriteLine(cwr.description);
Cwr<int> cwr2 = new Cwr<int>() { price = 1, courseName = 2, description = 4 };
Console.WriteLine(cwr2.description);
}
}
public class Cwr<T>
{
public T price { get; set; }
public T courseName { get; set; }
public T description { get; set; }
}
}
For Password Field:
To use data annotations for a password field, you can apply the following attributes to your model property:
Required: This ensures that the password field is not left blank or null.
StringLength: This sets the maximum and minimum length of the password, and optionally an error message to display if the validation fails.
DataType: This specifies the type of data that the password field should accept, and also affects how the field is rendered in the view. For passwords, you should use DataType.Password, which will hide the input characters with asterisks or dots.
Display: This sets the name of the field that will be shown in the view and in the error messages.
For example:
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
This means that the Password property must be at least 6 and no more than 100 characters long, and it will be displayed as “Password” in the view and in the error messages.
If you want to validate a confirm password field as well, you can use another attribute called Compare, which checks if two properties have the same value1.
For example:
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
This means that the ConfirmPassword property must match the Password property, and it will be displayed as “Confirm password” in the view and in the error messages. I hope this helps you use data annotations for password fields in C#. Do you have any other questions?
Regular Expression: Alphabet only
One way to validate that a string contains only alphabets is to use the RegularExpression attribute in your data annotation.
For example:
[RegularExpression(@"^[a-zA-Z]+$", ErrorMessage = "Use letters only please")]
string TextBoxData {get; set;}
Regular Expression: Numeric Data
To validate numeric data, you can use the Range attribute in your data annotation. This will check if the value is within a specified range of numbers.
For example:
[Range(0, int.MaxValue, ErrorMessage = "Please enter valid integer Number")]
int Number {get; set;}
This will validate that the value is an integer between 0 and the maximum value of int. You can also use different types of numbers such as float or double, and specify the minimum and maximum values according to your needs.
Email Address:
To validate an email field, you can use the EmailAddress attribute in your data annotation. This will check if the value is a valid email address format.
For example:
[Required(ErrorMessage = "The Email field is required.")]
[EmailAddress(ErrorMessage = "The Email field is not a valid e-mail address.")]
public string Email { get; set; }
This will validate that the value is not empty and matches the email address pattern. You can also customize the error messages if the validation fails.
Razor syntax is a way of embedding C# code into web pages using a few keywords and symbols. It allows you to write dynamic HTML that can be processed and converted at runtime.
For example: Write a code to print 1 - 5 using Razor Syntax.
@{
int[] nums = { 1, 2, 3, 4, 5 };
for(int i = 0; i < nums.Length; i++)
{
<h1>@nums[i]</h1>
}
}
For example: Write a code to print even and odd numbers side by side using Razor Syntax.
@{
int[] evenNumbers = { 2, 4, 6, 8, 10 };
int[] oddNumbers = {1,3,5,7,9};
for(int i = 0; i < evenNumbers.Length; i++)
{
<div class="container">
<div class="row">
<div class="col">
<h1>@evenNumbers[i]</h1>
</div>
<div class="col">
<h1>@oddNumbers[i]</h1>
</div>
</div>
</div>
}
}
LINQ (Language Integrated Query) is a feature of C# that allows you to write queries to access data from various sources, such as arrays, collections, databases, XML, etc. LINQ queries use a common syntax that is similar to SQL, but integrated into C#
For example: Write a code to print the even numbers from an array using LINQ.
public void FindEven()
{
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var even = from num in numbers
where num % 2 == 0
select num;
foreach(int num in even)
{
Console.WriteLine(num);
}
}
For example: Write a code to print all the names containing "F" from an array using LINQ..
public void FindName()
{
string[] names = { "Fuad", "Founder of University Notes - Code with Redoy" };
var mq = from name in names
where name.Contains('F')
select name;
foreach (var name in mq)
{
Console.WriteLine(name);
}
}
For example: Write a code to print all the ages (age < = 20) from an array using LINQ.
public void FindAge()
{
int[] ages = { 18, 20, 26, 24 };
var LINQ = from age in ages
where age <= 20
select age;
foreach(int age in LINQ)
{
Console.WriteLine(age);
}
}