The main purpose of "Dot Net Labs" provide the dot net program. You can learn dot net, .Net Core, C#, SQL, Linq step-by-step.

Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Sunday, 4 June 2023

How to Declaration and assign of variable in C#


Variable

Variable is a named storage location that holds a value of a particular data type. It is used to store and manipulate data during the execution of a program. Variables have a specific type, which determines the kind of data they can hold, such as integers, floating-point numbers, characters, Boolean values, or custom types.

In C#, variables can be of different types, each representing a specific kind of data. Here are some commonly used types of variables in C#:

Numeric Types:
    • int: Represents whole numbers (e.g., 42).
    • float: Represents single-precision floating-point numbers (e.g., 3.14f).
    • double: Represents double-precision floating-point numbers (e.g., 3.14).
    • decimal: Represents decimal numbers with higher precision (e.g., 3.14m).
    • byte: Represents unsigned integers (0 to 255).
    • short: Represents small integers (-32,768 to 32,767).
    • long: Represents large integers (-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807).

Character Types:
    • char: Represents a single character (e.g., 'A', '5', '$').

Boolean Type:
    • bool: Represents a Boolean value (either true or false).

String Type:
    • string: Represents a sequence of characters (e.g., "Hello, World!").

Enumerations:
    • enum: Represents a set of named values (e.g., days of the week, months).

Arrays:
    • type[]: Represents a collection of elements of a specific type (e.g., int[], string[]).

Object Type:
    • object: Represents any type of data (a reference to an instance of a class).

Create Variables

You can declare variables using the following syntax:

<type> <variableName>;

Here's an example of declaring variables of different types in C#:

int age; // declaring an integer variable named "age"
float temperature; // declaring a float variable named "temperature"
bool isStudent; // declaring a boolean variable named "isStudent"
string name; // declaring a string variable named "name"


You can also declare and initialize a variable in a single statement:

<type> <variableName> = <value>;

Here's an example:

int count = 0; // declaring and initializing an integer variable named "count" with a value of 0
float pi = 3.14f; // declaring and initializing a float variable named "pi" with a value of 3.14
bool isActive = true; // declaring and initializing a boolean variable named "isActive" with a value of true
string message = "Hello, world!"; // declaring and initializing a string variable named "message" with a value of "Hello, world!"

It's important to note that the variable name should follow certain rules:

    • It must start with a letter or underscore (_).
    • It can contain letters, digits, and underscores.
    • It cannot contain spaces or special characters (except underscores).

It's also recommended to use meaningful names for variables to make your code more readable and maintainable.

A demonstration of how to declare variables of different types with a screenshot:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace VariableDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            string Name = "Amit Kumar";
            int Age = 50;
            float num1 = 85.45f;
            double num2 = 524.2;
            char ch = 'A';
 
            Console.WriteLine("All information are :");
            Console.WriteLine(Name);
            Console.WriteLine(Age);
            Console.WriteLine(num1);
            Console.WriteLine(num2);
            Console.WriteLine(ch);
 
            Console.ReadLine();
 
        }
    }
}


Output: 


Thursday, 1 June 2023

What is Static Class in C# and when to use with real example


In C#, a static class is a class that cannot be instantiated and can only contain static members, such as static methods, static properties, and static fields. It is primarily used as a container for utility functions or extension methods that can be accessed without creating an instance of the class.

The main features of static classes are as follows:

  • They can only contain static members.
  • They can't be instantiated or inherited because static classes are sealed and can't contain instance constructors. However, the developer can create static constructors to initialize the static members.

The following code is an example of a static class. We have already learned that all members of the class are static.

       public static class Product

    {
        // Static fields because Product is a static class
        public static string Name = "Laptop";
        public static float Price= 500;
        public static DateTime ManufacturingDate = new DateTime(2023, 01, 01);
        public static string Location = "Delhi";
        public static int GetDeliveryCharge()
        {
            return 10;
        }
    }

Let's see the example of static classes with their characteristics

We can create an instance of static class if you create instance of class you will get compile time error like Cannot create an instance of the static class 'Product' let's see example in below picture.

What is Static Class in C# and when to use with real example

Static class cannot be inherited means you can child class from static class if you try to inherit static class then you will get compile time error 'MyItems' cannot drive from static class 'Product' let's see an example and try it yourself for best practice.

When To Use Static Classes In C#

We cannot create instance members in the static class otherwise you will get this error 'GetDeliveryCharge' can't declare instance members in a static class

What is Static Class in C# and when to use with real example


Now we will see how can call a static member of the static class to call a static member of a static class in C#, you can simply use the class name followed by the member name, without needing to create an instance of the class. Here's an example:

using System;
using System.Xml.Linq;
 
namespace SoftwareEngineerDotNet
{
    public static class Product
    {
        public static string Location = "Delhi";
        public static int GetDeliveryCharge()
        {
            return 10;
        }
    }
 
    class Program
    {
        static void Main(string[] args)
        {
            // Calling the static method
            int result = Product.GetDeliveryCharge();
            Console.ReadLine();
        }
    }
}


Note that static classes cannot be inherited, and they cannot have instance constructors. They are sealed by default, which means you cannot derive a class from a static class.


Saturday, 27 May 2023

Methods or Functions in C#


In C#, Methods and functions are both the same thing. In the article, we will learn everything about this topic. We will learn how to define a method in C#, what method is used for, how to call a method, and what different keywords are used with a method in C#.

Method

  • A method is a group of statements that together perform a task.
  • Methods are functions declared in a class and may be used to perform operations on class variables
  • They are blocks of code that can take parameters and may or may not return a value.
  • It is used to perform specific task.
  • Methods are reusable.
Remember: Every C# program has at least one class with a method named Main

Example:
How to create a method 

    class Program

    {

        //Declaring a method

        public void MyMethod()

        {

           //method body

        }

    }

public, it is an access specifier means it makes an accessible method.
void, it specifies what type of value a method returns. This method will not return any value.
MyMethod() is the name of the method which has a simple method and works as an identifier.

How to call a Method

If you have created a method named MyMethod() method then you need to call it. For calling you have to write the method's name followed by two parentheses () and a semicolon ; please see the example below.

    class Program
    {
        //Declaring a method
        public void MyMethod()
        {
            Console.WriteLine("My name is Method");
            Console.WriteLine("Methods are functions declared in a class only");
        }
 
        static void Main(string[] args)
        {
            //create class object
            Program program = new Program();

            program.MyMethod(); //Calling method

            Console.ReadLine();
        }
    }

        Output:
        My name is Method
        Methods are functions declared in a class only

You can call the method many times as per your requirement 
    
    class Program
    {
        //Declaring a method
        public void MyMethod()
        {
            Console.WriteLine("My name is Method");
            Console.WriteLine("Methods are functions declared in a class only");
        }
 
        static void Main(string[] args)
        {
            Program program = new Program();
            program.MyMethod(); //Calling method
            program.MyMethod(); //Calling method
            program.MyMethod(); //Calling method
            program.MyMethod(); //Calling method
            program.MyMethod(); //Calling method
            Console.ReadLine();
        }
    }

Method Parameters and Arguments
Parameters are variables or placeholders defined in a function or method declaration. Parameters are specified within the parentheses following the function or method name. They help define the input requirements and behavior of the function.

Arguments are the actual values passed to a function or method when it is called. When a function is called, the arguments provide the specific values that will be assigned to the function's parameters. The number and order of arguments must match the number and order of parameters defined in the function or method declaration.

we can also create a method with a single parameter

You can create a method with a single parameter or multiple parameters. In above picture you can see the method with a single parameter. Now you will see how can create a method with multiple parameters

using System;
using System.Xml.Linq;
 
namespace SoftwareEngineerDotNet
{
    class Program
    {
        //Declaring a method with multiple parameters
        public void MyMethod(string name, int age)
        {
            Console.WriteLine("Your name is "+ name);
        }
 
        static void Main(string[] args)
        {
            Program program = new Program();
            program.MyMethod("Amit Kumar", 35); //Calling method with multiple arguments
            program.MyMethod("John", 40); //Calling method with multiple arguments
            Console.ReadLine();
        }
    }
}

Many parameters should be separate with commas.
Method calls must have the same number of arguments as there are parameters  and the arguments must be passed in the same order and datatype.

What is default parameter value in C#

You can create a default parameter value using the equals sign ( = ). It is also known as an optional parameter. If you call the method without an argument then it will use default value.

default parameter value in c#

Method Return Values

Method may or may not return a value, we used void in above exmaple which indicates that the method should not return a value. If you want method return any value you can use primitive data types like int, double and use the return keyword inside the method.

how to return method in c#

Below is an example of two data parameters with return type method

class Program
    {
        //Declaring a method with the return value, multiple parameters
        public int Sum(int x, int y)
        {
            return 10 + x + y;
        }
 
        static void Main(string[] args)
        {
            Program program = new Program();
            Console.WriteLine(program.Sum(5, 10)); //Calling method
            Console.ReadLine();
        }
    }

Below is an example of two data parameters with return string but the return type is int

    class Program
    {
        //Declaring a method
        public int Sum(int x, int y)
        {
            return x + y + "Amit"; //Compile time error
        }
 
        static void Main(string[] args)
        {
            Program program = new Program();
            Console.WriteLine(program.Sum(5, 10)); //Calling method
            Console.ReadLine();
        }
    }

Below is an example of a method where you can store the result in a variable.

    class Program
    {
        //Declaring a method
        public int Sum(int x, int y)
        {
            return x + y;
        }
 
        static void Main(string[] args)
        {
            Program program = new Program();
 
            //Store the result in a variable
            int z = program.Sum(5, 10);
 
            Console.WriteLine(z); //Calling method
            Console.ReadLine();
        }
    }


Thursday, 25 May 2023

Senior .NET Developer Minimum and Maximum Salary


The minimum and maximum salary of .NET developers can vary significantly based on several factors. Here is a general overview of the salary range for .NET developers, but please note that these figures are approximate and can vary depending on location, experience, and other factors:


Minimum Salary:

For beginners or those with less experience, the starting salary for a .NET developer can range from ₹ 3.6 Lakhs to ₹ 7.8 Lakhs per year. This can vary based on where you live and the company you work for.

Maximum Salary:

As you gain more experience and expertise, your salary as a .NET developer can increase. Experienced or senior .NET developers can earn salaries ranging from ₹ 7.8 Lakhs to ₹ 30 Lakhs or even more each year. Again, the exact amount will depend on various factors such as your location and the size of the company.

Senior .NET Developer Salaries by Company



Remember, these figures are approximate and can vary based on factors like your skills, the demand for .NET developers in your area, and the industry you work in. It's always a good idea to research salary ranges specific to your location and job market to get a more accurate understanding of potential earnings.



Why Learning .NET Can Benefit You In 2023


.NET is a popular framework used for creating different types of applications. Whether you're new to programming or experienced, learning .NET offers many advantages. In this article, we'll explore why learning .NET is worth your time and effort.


Works on Different Platforms:

One great thing about .NET is that it can run on various operating systems like Windows, macOS, and Linux. This means you can build apps that work on different devices without major changes. Whether you're making websites, desktop programs, or mobile apps, .NET provides the tools to make development easier across different platforms.



Reliable and Scalable:

.NET offers a strong foundation for creating apps of any size or complexity. It comes with a wide range of ready-made components and features, saving you time and effort. You can easily work with databases, handle networks, ensure security, and integrate with other services. Plus, .NET allows your apps to handle increased workloads as they grow, adapting to meet users' needs.

Wide Range of Tools:

Learning .NET opens doors to a wealth of development tools. Integrated development environments (IDEs) like Visual Studio and Visual Studio Code provide advanced features for coding, debugging, and testing. The open-source nature of .NET Core fosters a supportive community that creates libraries and frameworks. By tapping into this collective knowledge, you can speed up your development process and solve common programming challenges.

Abundant Job Opportunities:

Acquiring .NET skills can lead to exciting career prospects. Many businesses, including big names like Microsoft, rely on .NET for their software needs. As a result, there is high demand for skilled .NET developers. By mastering .NET, you open up opportunities in roles such as software developer, web developer, systems analyst, or even freelancing. The versatility and marketability of .NET skills make them valuable in the tech industry.



So why wait?

Start your .NET journey today and unlock endless possibilities.

Learning .NET is a smart move for developers at any level. Its compatibility across platforms, robust framework, useful development tools, and career opportunities make it a valuable skillset. By learning .NET, you gain the ability to create powerful applications, contribute to a supportive community, and advance your career in the ever-changing world of software development.

Monday, 22 May 2023

Introduction to Arrays in C#


 Array

In C#, an array is a data structure that stores a fixed-size sequence of elements of the same type. Arrays are widely used in programming for tasks that involve working with collections of data, such as storing a list of numbers, strings, or objects.

Example :      int[] numbers = new int[5];

Describe:

  • An array always stores values of a single data type

          Example:

          int[] numbers = {2,4,5,7};   //allow single data type


          int[] numbers = {2,4,5,"Amit" };  //compile error, convert type string to int

  • C# supports zero-based index values in an array
          Example:
          int[] numbers = { 1, 2, 3, 4, 5 };
          
  • Arrays have a fixed length, means that once your create an array with a specific size, you cannot change its size later, The size of an array is determined at the time of its declaration.
            int[] myarray = new int[4];

            myarray[0] = 1;
            myarray[1] = 2;
            myarray[2] = 3;
            myarray[3] = 4;

Declaring Arrays

Sunday, 21 May 2023

Friday, 19 May 2023

What is C# and its features



C# is an Object Oriented  Programming Language (OOP). The common traits are encapsulation, inheritance and polymorphic.

All the C# files are saved with file extension .CS

C# includes the following five types of tokens.

  • Keywords
  • Identifies
  • Literals
  • Identifies
  • Operators
  • Punctuates

Programming Language is a process of creating computer programs or in the other word software to solve a particular problem.

C# is developed by Microsoft Corporation in year 2000.

C# can be used to build variety of applications. There are following example of applications developed by c#.

Window Application using WinForm Or WPF

Mobile Application for Phones such as Nokia Lumia (Native support) But you can use a 3rd party library called "Xamarin" to create mobile application for Android and IOS as well.

Web Application using Asp.net web forms or asp.net MVC.


As per the interview perspective this is question is very important so please try to learn in-depth for good impression.


What is C# and latest version of C#?


What is C#?

C# stands out as a powerful and versatile language. It is a modern, object-oriented programming language that was introduced by Microsoft in the early 2000s, C# provides a flexible and efficient platform for building a wide range of applications, from desktop software to web applications and even mobile apps. C# is specifically designed to run on the .NET Framework, which provides a comprehensive set of libraries and tools for developing applications on the Windows platform.


Key Features of C#:

Object-Oriented Approach: C# follows the principles of object-oriented programming (OOP), enabling developers to create reusable and modular code through the use of classes, objects, inheritance, and polymorphism.


Type Safety: C# is a statically-typed language, which means that all variables and expressions must have a specific data type defined at compile-time. This ensures type safety and helps catch errors early in the development process.


Memory Management: C# utilizes automatic memory management through a process known as garbage collection. This feature helps simplify memory management tasks by automatically clearing memory that is no longer in use, reducing the risk of memory leaks and improving application performance.


Language Interoperability: C# is designed to be language interoperable, allowing developers to integrate code written in different languages such as Visual Basic .NET and C++ into the same application. This interoperability enhances code reusability and promotes collaboration among developers.


Exception Handling: C# provides robust support for handling exceptions, allowing developers to catch and handle errors gracefully during the execution of their programs. This helps improve the reliability and stability of applications, making them more resilient to unexpected issues.


Latest Version of C#:

The latest stable version of C# is C# 10, which was released along with .NET 6.0 in November 2022. You can use its feature with the .Net 7 SDK.


Note: C# 12 features have been introduced in previews.



Popular Posts