Software Training Institute in Chennai with 100% Placements – SLA Institute

Easy way to IT Job

Share on your Social Media

Top 40 C Sharp Interview Questions and Answers

Published On: December 10, 2024

According to the TIOBE ranking for 2024, C# is the language with the fastest rate of growth. Leading software companies worldwide are in great demand for it. Jobs requiring C sharp will always be in demand. Use our carefully crafted list of the top 40 C-sharp interview questions and answers to be picked quickly. Before you begin, review our C-Sharp course syllabus.

C Sharp Interview Questions for Freshers

Here are the basic C-sharp interview questions and answers for freshers. 

Interview Questions on Core C# Concepts

1. Differentiate ref and out parameters in C#.

Ref: A crucial idea in C# is the ref keyword, which enables you to send parameters to methods by reference as opposed to value. By passing a reference to the original variable when you use ref, you allow the method to change the value of the actual variable.

Out: As a parameter modification, it enables you to supply a method with an argument via reference instead of value. This indicates that a type parameter is covariant in generic type parameter declarations for interfaces and delegates.

2. Explain the concept of garbage collection in C#.

A memory recovery function called garbage collection (GC) is a characteristic of C#. 

  • One or more garbage collectors, also known as GC engines, are built into programming languages that support GC. 
  • These engines automatically clear out memory space that has been occupied by things that the program no longer needs.

3. What is the difference between value type and reference type in C sharp?

Reference types store pointers to their data, but value types in C# store their data directly. This is the primary distinction between the two kinds.

Value types: There is a copy of the data for every variable. 

  • Value types are typically more memory- and performance-efficient. 
  • They are frequently immutable, which means that once they are created, their value cannot be altered.

Reference type: When two variables reference the same object, changes made to one of them may have an impact on the object that the other variable is referencing. 

  • Although reference types are more versatile and potent than value types, improper handling of them may result in unexpected consequences. 
  • Both mutable and immutable reference types are possible.  

4. What is boxing and unboxing in C sharp?

Data conversion between value types and reference types in C# is accomplished through the boxing and unpacking processes.

Boxing: Changes a value type into an interface or object type. The value type of a System.Object instance is wrapped by the common language runtime (CLR) and stored on the managed heap. It is implicit.

Unboxing: Value type is extracted from the item during unpacking. The unboxing process is explicit.

5. Explain the concept of polymorphism in C#.

A key idea in object-oriented programming (OOP) is polymorphism, which in C# enables objects of various classes to be regarded as though they were members of the same base class. The word “polymorphism” means “many-shaped” in Greek.  

There are two primary features of polymorphism in C#:

  • Run-time: It is possible to treat derived class objects as base class objects. Variables such as arrays, collections, or function arguments may experience this.
  • Virtual methods: Derived classes can override virtual methods that base classes specify and implement. 

6. What is the difference between abstract and virtual keywords in C#?

The primary distinction between the abstract and virtual keywords in C# is that, whereas virtual methods can be overridden in derived classes, abstract methods need derived classes to provide their own implementation.

  • Abstract keyword: These methods need to be overridden in derived classes because they lack an implementation.
    • Only abstract methods may be included in abstract classes, which are not immediately instantiable.
  • Virtual keyword: Derived classes can override the default implementation of these methods.
    • Both abstract and non-abstract classes may contain virtual methods.  

7. What is the use of the sealed keyword in C#?

In C#, the sealed keyword stops methods or classes from being overridden or inherited.

  • Classes: The sealed keyword stops other classes from inheriting from a class when it is applied to that class. Class B is sealed, for instance, if it inherits from class A but no other class can inherit from class B.
  • Properties or methods: The sealed keyword stops derived classes from overriding a method or property that overrides a virtual method or property in a base class.  

The programmer has control over how extensible and editable the code is because of the sealed keyword. The sealed keyword is frequently used for utility classes, preventing subclassing, and security.

8. What is the difference between override and new keywords in C#?

In C#, the new keyword conceals a base class method, but the override keyword extends a virtual method in a base class:

  • Override keyword: In a base class, override extends a virtual method. You must declare the function as virtual to use this keyword. You will receive an error if the original function is not implemented as virtual.
  • New keyword: A base class method is hidden by New. Additionally, this keyword doesn’t need any additional restructuring and suppresses warning warnings.

These keywords govern the implementation and access to inherited members in derived classes. Writing reliable and maintainable object-oriented programs requires knowing how to use them properly.  

9. What is the difference between static and instance members in C#?

Static members are seen as belonging to the class, whereas instance members are connected to instances of a type. A static member can be accessed by using the class name where it is declared. 

Get started with our C# online course program

Interview Questions on C# Language Features

10. What is LINQ? Explain its benefits.

A collection of technologies known as Language Integrated Query (LINQ) enables programmers to query, alter, and update data from several sources in C#. It immediately incorporates querying functionality into the C# programming language. 

The following are some advantages of LINQ: 

  • Conciseness and readability: Particularly when filtering numerous conditions, LINQ queries are more clear and more succinct than conventional foreach loops. 
  • Filtering, ordering, and grouping: LINQ offers robust grouping, filtering, and ordering features with little application code. 
  • Easier deployment: Compared to stored procedure-based apps, LINQ-based applications are simpler to deploy. 
  • Consistent query experience: LINQ offers a standardized query experience for XML, relational databases, and objects. 

11. Differentiate foreach and for loops in C#.

Foreach in C#For Loop in C#
For every element in the array, it runs a statement or a block of statements. Until the specified condition is false, a statement or block of statements is executed. 
Doesn’t need boundaries to be established.Focuses on the upper and lower bounds.
Only forward.Both forward and backward iterations of the array are performed. 
There are five variable declarations in the foreach loop.There are just three variable declarations in a for loop. 
Just a variable declared with the same data type as the collection’s base is required.It makes use of the loop counter variable. 
It makes a copy of the array for the operation.No array copies are created.

12. What is the yield keyword in C# used for?

Programmers can loop through a collection of objects one at a time using the yield keyword in C# to create an iterator method.

By informing the compiler that a method is an iterator block, the yield keyword causes the compiler to return an IEnumerable. The values for the IEnumerable are then returned with the yield keyword. 

Code can be made simpler, more effective, and easier to understand by using the yield keyword.  

Syntax:

yield return value

The following statements can be used with the yield keyword:

  • yield return: Gives the iterator’s subsequent value.
  • yield-break: Indicates that an iteration is finished. 

13. Explain the concept of delegates and events in C#.

In C#, actions, or methods, are dynamically assigned and triggered using delegates and events. Though they have diverse functions, they are connected to event handling: 

  • Delegates: You can store methods in variables or provide them as parameters using this type-safe function pointer.
    • In C and C++, delegate is comparable to function pointers. 
    • They are frequently saved as members of the private class and provided as arguments.
  • Events: A notification system reliant on delegates. Delegate usage is further secured via events, which serve as wrappers over delegates. Usually, class members attend events.  

14. Define params in C#.

Code becomes more flexible and efficient when developers use the params keyword to pass in a variable number of parameters at once. 

In C#, parameters are a crucial keyword. This option is used to accept a configurable number of parameters. It is helpful in situations where programmers are unsure of how many parameters to use.

15. What is the use of the using statement in C#?

In C#, the using statement provides various purposes, such as: 

  • Ensuring correct use of disposable objects: Even in the event of an exception, the “using” statement guarantees that an IDisposable instance is utilized appropriately and disposed of. 
  • Defining scope: The using statement guarantees that objects are appropriately disposed of when the scope is vacated and establishes a scope within which they can be used. 
  • Importing namespaces: Namespaces can be imported at the beginning of a code file using the using statement. 
  • Creating aliases: Aliases can be created for a namespace using the utilizing directive. 

16. What is the difference between try-catch and try-finally blocks in C#?

The following keywords are used in C# exception handling:

try: A try block indicates a code block that has certain exceptions enabled. One or more catch blocks come after it.

catch: A program uses an exception handler to catch an exception at the specific location where you wish to address the issue. The catch keyword denotes that an exception has been caught.

finally: Whether or not an exception is raised, a specified sequence of statements is executed using the “finally” block. For instance, whether or not an exception is raised, a file must be closed after it has been opened.

Example: try-finally:

try {

   result = num1 / num2;

} catch (DivideByZeroException e) {

   Console.WriteLine(“Exception caught: {0}”, e);

} finally {

   Console.WriteLine(“Result: {0}”, result);

}

17. What is the use of the async and await keywords in C#?

Writing asynchronous code in C# with the async and await keywords enables a program to carry out other activities while it waits for a lengthy action to finish.

  • async: It allows a method to use the await keyword in its body by designating it as asynchronous.
  • await: Until the awaited job is finished, await pauses the calling method and returns control to its caller. 

You should be aware of the following regarding async and await:

  • The async keyword can be used with anonymous methods, lambda expressions, and methods.
  • Any expression that returns a Task or Task<object> object can use the await keyword.
  • Only async methods are permitted to utilize the await keyword.
  • An exit from the method does not occur when an async method is suspended at an await expression.
  • For contemporary applications like client and server programs, asynchronous programming is essential.

18. Explain the concept of extension methods in C#.

The extension method in C# enables you to add new methods to an existing class or structure without changing the original type’s source code. 

You also don’t need to recompile the original type or get any specific permission from it. In C# 3.0, it is first introduced.

19. What is the difference between var and dynamic keywords in C#?

The primary distinction between the var and dynamic keywords in C# is that the var is used for static typing during compilation, whereas the dynamic is used for dynamic typing during runtime.

  • Var: Declared variables with implicit typing are those whose type is automatically determined by the compiler during compilation. Static typing can be strengthened and improved with Var. 
  • Dynamic: Dynamic variables are created using dynamic type, in which the type is not determined at compile time by the compiler. Instead of using static typing, dynamic enables late-bound behavior. 

Explore our article that covers c and c++ interview questions and answers

Advanced C# Interview Questions and Answers for Experienced

Here are the C# interview questions and answers for experienced professionals.

C#.NET Framework Interview Questions and Answers

20. What is C#.NET?

Applications are created using the programming languages C# and.NET.

  • C#: Media, finance, healthcare, and gaming are just a few of the industries that employ C#, a contemporary object-oriented programming language.
    • As it’s simple to learn and well-known to developers with prior experience with JavaScript, Java, or C++, C# is widely used.
  • .NET Framework: An open-source platform for developers that offers tools for creating apps together with a common collection of libraries and APIs.
    • The operating systems Windows, Linux, Apple, and Android all support .NET.  

21. Explain the concept of assemblies and modules in C#.

An assembly is a grouping of one or more modules that together form an application in C#. 

  • A code file with type metadata inside an assembly is called a module. 
  • The fundamental unit of deployment for .NET-based programs and the building blocks of C# applications are assemblies.  

Example: Assemblies:

public class PrivateAssembly {

  public int Add(int n1, int n2) {

    int res = n1 + n2;

    return res;

  }

  public int diff(int n1, int n2) {

    int res = n1 – n2;

    return res;

  }

}

Example: Modules:

using System.Reflection;

using System;

public class Program {

    public static void Main() {

        Class1 c1 = new Class1();

        //  Show the current module.

        Module m = c1.GetType().Module;

        Console.WriteLine(“The current module is {0}.”, m.Name);

        //  List all modules in the assembly.

        Assembly curAssembly = typeof(Program).Assembly;

        Console.WriteLine(“The current executing assembly is {0}.”, curAssembly);

        Module[] mods = curAssembly.GetModules();

        foreach (Module md in mods) {

            Console.WriteLine(“This assembly contains the {0} module”, md.Name);

        }

        Console.ReadLine();

    }

}

class Class1 {

}

22. What is the Common Language Runtime (CLR) in C#?

Microsoft’s .NET Framework includes a virtual machine component called the Common Language Runtime (CLR) that controls and runs C# programs.

  • Execution engine: For running programs, the CLR offers features like type-safety, garbage collection, thread management, and exception handling.
  • Runtime environment: Developers can concentrate on writing high-level code since the CLR takes care of low-level aspects like memory allocation and security.
  • Portable execution: Any Windows 2000 or Windows XP system can run programs compiled for the CLR.
  • Language interoperability: A class written in one language can invoke a method of a class written in another language due to the CLR.
  • Just-in-time compilation: Managed code is transformed into machine instructions by the CLR, which are subsequently carried out by the CPU. 

23. What is the role of the Just-In-Time (JIT) compiler in C#?

The Microsoft Intermediate Language (MSIL) or Common Intermediate Language (CIL) is transformed into machine code by the C# Just-In-Time (JIT) compiler. 

The function of the JIT compiler is to:

  • Speed up code execution: Machine code, which is quicker and easier to understand than the original bytecode, is created from bytecode sequences by the JIT compiler.
  • Multiple platform support: A JIT compiler is required to support numerous platforms.
  • Only compile what’s needed: The entire file is not compiled by the JIT compiler; only the necessary CIL or MSIL is.
  • Re-optimize code: To increase performance, the JIT compiler finds code segments that can be reoptimized.

24. What is the difference between AppDomain and Process in C#?

AppDomain: A process’s isolation unit is called an AppDomain. Runtime creation, code loading, and unloading are all possible for AppDomains. It is an isolation border intended to increase the dependability of.NET applications.

Process: A process is an executing application. OS employs processes to make it easier for programs to run. A process is a program’s “RAM representation” with address space made up of the stack, heap, static, and code regions. Every process has a distinct process ID linked to it.

25. What is the difference between strong naming and delay signing in C#?

Delay signing is a method for creating a partial signature while developing in C#, whereas strong naming is the process of signing an assembly with a key. 

Strong naming: It gives an assembly a distinct identity depending on its version number and name. 

  • Strong-named assemblies are kept in the Global Assembly Cache (GAC) and can be utilized and referenced by other strong-named assemblies. 
  • Strong naming is vulnerable to hacking, and Microsoft stresses that digital signing offers a higher degree of confidence.  

Delay signing: It enables you to use just the public key to create a partial signature while it is being developed. 

Before delivering the code, the final strong name signature can be applied using the private key, which can be kept safe. To employ delay signing, you must:

  • Obtain the key pair’s public key component from the company that will perform the final signature.
  • Add two custom attributes to the assembly’s source code annotation.
  • Set up your development computers to forego verifying your key’s strong name signature.

The Strong Name program (Sn.exe) can be used to perform delay signing and generate the public key.  

Learn from scratch with our .NET training in Chennai. 

26. What is the role of the System.IO namespace in C#?

Numerous classes in the System.IO namespace are used to carry out a variety of file-related tasks, including reading from or writing to files, shutting files, and creating and deleting files. 

It includes types that offer simple file and directory functionality as well as types that enable reading and writing to files and data streams.

Some of the classes in System.IO namespace:

  • BinaryReader: It reads binary values in a particular encoding representing primitive data types.
  • BinaryWriter: It allows writing strings in a certain encoding and writes primitive types in binary to a stream.
  • BufferedStream: A buffering layer is added by BufferedStream to enable read and write operations on a different stream. It is not possible to inherit this class.
  • Directory: Static methods for creating, navigating, and listing directories and subdirectories are exposed by Directory. It is not possible to inherit this class. 
  • DirectoryInfo: Instance methods for creating, navigating, and listing directories and subdirectories are exposed by DirectoryInfo. It is not possible to inherit this class.

27. What is the role of the System.Collections namespace in C#?

Classes and interfaces defining collections and mechanisms for collecting, classifying, and organizing data or items are found in the System.Collections namespace in C#.

Non-generic collections: These collections can contain any form of data because they store elements in object arrays. Casting is necessary for adding or removing things, and they are frequently utilized in older code. 

Generic  collections: These collections usually perform better than non-generic collections and are type-safe at compile time. They don’t need to be cast to and from the Object type, and they can be built using a type argument. 

  • System.Collections.Concurrent namespace: To access collection elements from many threads, this namespace offers thread-safe procedures. 
  • System.Collections.Immutable namespace: Immutable collection classes that are intrinsically thread-safe are contained in this namespace. 
  • Abstract base classes: Strongly typed collection classes can be created by extending them, which include CollectionBase, ReadOnlyCollectionBase, and DictionaryBase. 

28. What is the role of the System.Threading namespace in C#?

Program performance can be enhanced by using the classes and methods for working with threads that are available in the System.Threading namespace in C#.

  • Thread class: Generates and retrieves threads, including the main thread’s offspring.
  • Thread-local storage: Offers data storage
  • Thread pool: Offers a collection of threads for jobs, timers, and other purposes. 
  • Synchronization data structures: Channels for data transmission between producers and consumers are provided by synchronization data structures. 
  • Volatile memory operations: Offers techniques for carrying out volatile memory operations.
  • Operating system-specific objects: Encapsulating items that await exclusive access to shared resources are operating system-specific objects. 

A program can increase overall performance and decrease the amount of CPU cycles wasted by utilizing threads.

29. What is the role of the System.Data namespace in C#?

How to manage data in a DataSet is specified by the System.Data namespace in C#, which includes:

  • DataColumn Mapping.
  • Taking care of missing mappings.
  • Adding data to a DataSet while managing missing DataTables or DataColumns.
  • Defining query parameter types.
  • Defining the attributes of the property.
  • Managing ForeignKeyRestrictions.
  • Schema serialization for typed data sets.
  • Taking care of current schema mappings.
  • Identifying a DataSet’s serialization format.
  • Choosing data types for fields and attributes that are unique to SQL Server.

In C#, namespaces are used to create globally distinct types and arrange code pieces. In big projects, they can be used to limit the scope of class and method names. 

Explore our ASP.NET course syllabus to learn further. 

C# Interview Questions on Design Patterns

30. Explain the Singleton design pattern in C#.

A single point of access to a class and the guarantee that it has only one instance are provided by the C# Singleton design pattern, a creational design pattern. 

When one instance of a class is required to coordinate tasks, such as database connections, logging, or configuration setting management, it is helpful.  

Example Code for Singleton Design Pattern in C#

using System;

namespace SingletonDemo

{

    class Program

    {

        static void Main(string[] args)

        {

            //Call the GetInstance static method to get the Singleton Instance

            Singleton fromTeachaer = Singleton.GetInstance();

            fromTeachaer.PrintDetails(“From Teacher”);

            //Call the GetInstance static method to get the Singleton Instance

            Singleton fromStudent = Singleton.GetInstance();

            fromStudent.PrintDetails(“From Student”);

            Console.ReadLine();

        }

    }

}

31. Explain the Factory design pattern in C#

An interface for producing objects is defined by the C# Factory Design Pattern, a creational design pattern that lets subclasses choose which class to instantiate. 

There are various advantages to this pattern, including: 

  • Decoupling: The process of decoupling involves separating the code that generates the objects from the code that consumes them.
  • Flexibility: Facilitates the addition of new object types without requiring modifications to the code that utilizes them.
  • Loose coupling: It encourages loose connections between objects, which can improve software systems’ scalability and maintainability. 

The following are some C# instances of the Factory Design Pattern:

  • Vehicle Factory: Oversees the creation of automobiles, giving customers access to different models without being aware of their exact classes.
  • Soccer: Creating objects like a sketch is the responsibility of the creator class.
  • Abstract Factory: Although it offers an additional degree of abstraction, the Abstract Factory pattern is comparable to the Factory pattern. It enables you to construct families of related things without having to know the precise classes of those objects.  

32. Explain the Observer design pattern in C#

In C#, objects can alert other objects when their state changes by using the Observer design pattern, which is a behavioral pattern.

How it operates: A provider registers with zero or more observers; they are also referred to as subjects or observables. The provider automatically alerts all observers when a condition, event, or state changes.

Advantages: In situations where push-based notifications are necessary, the Observer pattern can be helpful. It aids in the creation of reusable and adaptable object-oriented software.  

Participants: The participants in the observer design pattern are:

  • Subject: It offers an interface for attaching and removing observers and is aware of its observers
  • Observer: It specifies an interface for updating objects that need to be informed when a subject changes.

Example: The Observer pattern can be used by a stock market program to monitor price fluctuations. To get updates on particular stocks, different investors can sign up.

The primary distinction between the Observer and Publisher-Subscriber (Pub-Sub) patterns is that the Observer pattern involves the subject keeping a direct list of observers.  

33. Explain the strategy design pattern in C#.

An algorithm’s behavior can be chosen at runtime using the C# Strategy design pattern, which is a behavioral design pattern. It’s a popular pattern in C# code that allows you to modify a class’s behavior without having to extend it.  

Key elements of the strategy design pattern include the following:

  • Encapsulate algorithms: A family of algorithms is defined by the pattern, which also encapsulates each one and renders them interchangeable.
  • Separate classes: To facilitate easy swapping when necessary, the algorithms are organized into distinct classes.
  • Context object: A strategy object is referenced by the original object, often known as the context.
  • Delegate work: The associated strategy object is tasked by the context with carrying out the activity.
  • Replace strategy object: To alter how the context functions, other objects can take the place of the strategy object that is now linked.  

When a class has several ways to carry out an action and the preferred method is decided at runtime, the strategy pattern can be helpful.

For example, adding a new payment method to a system without altering the existing code is possible with the strategy pattern.  

34. Explain the Decorator design pattern in C#

In C#, new behaviors can be introduced to objects without changing their structure thanks to the Decorator design pattern. Another name for it is the wrapper pattern.

The following are some essential elements of the decorator pattern:

Participants: There are four participants in the pattern:

  • Component: Declares the common interfaces for wrappers and wrapped objects.
  • Concrete Component: The class of objects that will be wrapped is the concrete component.
  • Base Decorator: All activities are delegated to the wrapped object after reference to it.
  • Concrete Decorator: Additional actions that can be added to concrete components are defined by the Concrete Decorator.
  • Client: Covers elements with many coats of decorators.

Recursion: A chain of responsibility can be established by adding decorators to other decorators.

When to apply: When you wish to add additional functionality to an existing class without changing it, the Decorator pattern can be helpful. A class with several responsibilities can also be divided into smaller classes using this method.

Example

A well-known illustration of the Decorator pattern in action is the CryptoStream class found in the .NET framework. By encrypting data before writing to the stream, it wraps the stream and expands its functionality.

Enhance your skills with our advanced .NET training in Chennai

Interview Questions on C# Performance and Optimization

35. What is profiling and how can it be used to optimize C# applications?

In C#, profiling is a technique for keeping an eye on an application’s operation to spot potential resource or performance issues. Time and resources can be saved by ensuring that an application operates effectively.

An application’s execution can be tracked via a profiler. Finding the sections of a program that are run the most frequently or where most of the time is spent can be useful. Profilers can give an application’s CPU utilization and execution times a visual representation, which can facilitate speedy decision-making.  

Additional points for C# software optimization are as follows:

  • Caching: Keep frequently used data in memory so that it can be rapidly retrieved without requiring a database or other data storage query.
  • Lazy Initialization: To speed up startup and save memory, wait until items are needed before initializing them.
  • Compiler Optimizations: Trust the C# compiler to carry out several optimizations.  

36. Explain caching in C#.

In C#, caching is a method that temporarily saves data for easier access. Applications’ scalability and performance may be enhanced as a result, particularly when handling massive volumes of data or data that changes infrequently.  

The following information relates to C# caching:

How it operates: The program can use the cache rather than the actual source to obtain data when it is required. Response times may be accelerated as a result of less strain on the original source. 

Caching types: C# has a variety of caching options, such as distributed caches and in-process persistent caches.

  • In-Memory Cache: The web server’s RAM contains this cache.  
  • Distributed Cache: A real server, like a Redis database, houses this cache. Compared to in-memory caches, distributed caches can accommodate greater scale-out.  

Caching in the .NET Framework: The .NET Framework offers caching feature in the System.Runtime.Caching namespace. 

Caching in ASP.NET Core: The IMemoryCache is one of the caches that ASP.NET Core supports. 

Caching expiration: Cached items may be scheduled to expire based on their frequency of access or after a predetermined period of time.

37. How can you avoid memory leaks in C# applications?

Memory leaks can be avoided by adhering to memory management best practices, which include using automated memory management tools, allocating and releasing memory appropriately, and regularly analyzing memory usage to spot possible leaks and fix them before they become an issue.

Tools to Diagnose Memory Leaks: The source of memory leaks in a software program can be found with the aid of debugging tools, memory profiling tools, and memory leak detection tools, among other diagnostic tools. 

How to Fix Memory Leaks: Resolving memory leaks entails locating the leak’s origin, such as a particular software application function or module, and putting appropriate memory management strategies into place to guarantee that memory is allocated and released appropriately. 

To fix memory leaks, this can entail replacing software components, changing the code, or utilizing memory profiling tools.

38. What distinguishes the Equals() method from the Equality Operator (==) in C#?

Both are utilized differently, even though they are both used to compare two objects based on their values. 

Equality operator: Reference-based comparison.

Equals(): Value-based comparison.

Example

int x = 10;

int y = 10;

Console.WriteLine( x == y);

Console.WriteLine(x.Equals(y));

Output:

True

True

Equality operator (==): The equality operator (==) is a reference type, meaning that it will only return true if both references point to the same property.  

Equals() method: The Equals method compares the values that the objects carry. int x=10, int y=10. When x==y is compared, the values that are carried by x and y are compared, and since they are equal, they return true. 

39. Create a C# application that determines whether a positive integer is prime.

 static void Main(string[] args) 

    if (FindPrime(47)) 

    { 

        Console.WriteLine(“Prime”); 

    } 

    else 

    { 

        Console.WriteLine(“Not Prime”); 

    } 

    Console.ReadLine(); 

}   

internal static bool FindPrime(int number) 

    if (number == 1) return false; 

    if (number == 2) return true; 

    if (number % 2 == 0) return false; 

     var squareRoot = (int)Math.Floor(Math.Sqrt(number)); 

     for (int i = 3; i <= squareRoot; i += 2) 

    { 

        if (number % i == 0) return false; 

    } 

     return true; 

}

40. Create a C# Sharp application that reverse the provided words’ order.

internal static void ReverseWordOrder(string str) 

  int i; 

  StringBuilder reverseSentence = new StringBuilder(); 

   int Start = str.Length – 1; 

  int End = str.Length – 1; 

   while (Start > 0) 

  { 

      if (str[Start] == ‘ ‘) 

      { 

          i = Start + 1; 

          while (i <= End) 

          { 

              reverseSentence.Append(str[i]); 

              i++; 

          } 

          reverseSentence.Append(‘ ‘); 

          End = Start – 1; 

      } 

      Start–; 

  } 

   for (i = 0; i <= End; i++) 

  { 

      reverseSentence.Append(str[i]); 

  } 

  Console.WriteLine(reverseSentence.ToString()); 

}

Conclusion

To strengthen your understanding, don’t forget to perform coding tasks, go over C# documentation, and look at real-world examples. Would you like to practice solving coding puzzles or learn more about a particular subject? Then, join our C# training in Chennai at SLA.

Share on your Social Media

Just a minute!

If you have any questions that you did not find answers for, our counsellors are here to answer them. You can get all your queries answered before deciding to join SLA and move your career forward.

We are excited to get started with you

Give us your information and we will arange for a free call (at your convenience) with one of our counsellors. You can get all your queries answered before deciding to join SLA and move your career forward.