Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Front Back
- How do you declare a variable of type int in C#? int x;
- What keyword is used to define a constant variable? const
- How do you write a single-line comment in C#? // This is a comment
- What is the default value of an uninitialized int variable in C#? 0
- How do you print 'Hello, World!' to the console? Console.WriteLine("Hello, World!");
- What keyword is used to create a method in C#? void (or return type)
- How do you declare a string variable? string name;
- What is the entry point method in a C# console application? Main
- How do you perform integer division in C#? Using the / operator (e.g., 5 / 2 results in 2)
- What is the modulus operator in C#? % (returns remainder of division)
- How do you declare a loop that runs exactly 10 times? for (int i = 0; i < 10; i++)
- How do you check for equality between two variables in C#? ==
- What is the keyword to define a new instance of a class? new
- How do you create an array of integers with 5 elements? int[] numbers = new int[5];
- What is the difference between == and Equals() in C#? == checks reference equality for reference types, while Equals() checks value equality when overridden.
- How do you declare a nullable integer variable? int? x;
- What is the difference between a struct and a class in C#? A struct is a value type stored on the stack, while a class is a reference type stored on the heap.
- How do you handle exceptions in C#? Using try-catch blocks
- What keyword is used to exit a loop prematurely? break
- How do you check if a string is null or empty in C#? string.IsNullOrEmpty(value)
- What is the difference between ref and out parameters? Both pass arguments by reference, but out requires the variable to be initialized before method return, while ref requires initialization before passing.
- How do you declare a readonly field in a class? readonly int x;
- What does the 'using' statement do in C#? It ensures the correct disposal of an IDisposable object.
- How do you format a string using interpolation? $"Hello {name}"
- How do you declare a multi-line comment in C#? /* This is a multi-line comment */
- What is an implicit conversion? A conversion that happens automatically when there is no risk of data loss.
- What is an explicit conversion? A conversion that requires a cast because data loss might occur.
- How do you convert a string to an integer safely? int.TryParse(string, out int result)
- What is the purpose of the var keyword? It allows implicit typing when the compiler can infer the type.
- What is a nullable reference type? A reference type that can explicitly be set to null in a nullable-enabled context.
- How do you declare a switch expression in C#? var result = value switch { 1 => "One", _ => "Other" };
- What is the difference between a class and an interface? A class has an implementation, whereas an interface only defines contracts that a class must implement.
- What is a lambda expression? A concise way to represent an anonymous function.
- How do you declare an auto-implemented property? public string Name { get; set; }
- What is the purpose of the is keyword? It checks if an object is of a specific type.
- What is pattern matching in C#? It allows matching on types and values within switch expressions or is checks.
- How do you declare a readonly struct? readonly struct MyStruct { }
- How do you check if an object is null in a modern, safe way? if (obj is null)
- What is the difference between a for loop and a foreach loop? A for loop is index-based and allows modifying the loop variable, whereas foreach iterates over elements and is read-only.
- What is the default access modifier in C#? private for class members, internal for top-level types.
- How do you create a tuple in C#? var tuple = (1, "Hello", true);
- What is the difference between an abstract class and an interface? An abstract class can have method implementations, while an interface only defines method signatures.
- What is an indexer in C#? An indexer allows instances of a class to be accessed like an array.
- What is the difference between IEnumerable and IQueryable? IEnumerable executes queries in memory, while IQueryable allows query execution on a remote data source.
- Front Back
- How do you check if a list contains a specific value in C#? list.Contains(value);
- What is the difference between List<T> and an array? List<T> is dynamic in size, whereas an array has a fixed size.
- How do you remove an element from a List<T>? list.Remove(value);
- What is the difference between == and ReferenceEquals in C#? ReferenceEquals checks if two objects reference the same memory location.
- How do you iterate through a dictionary in C#? foreach (var kvp in dictionary) { }
- What does the ?? operator do in C#? It provides a default value if the left-hand operand is null.
- What does the ?. operator do in C#? It performs a null-safe member access.
- How do you create a delegate in C#? delegate void MyDelegate();
- What is the difference between Func<T> and Action<T>? Func<T> returns a value, whereas Action<T> does not return a value.
- What is an expression-bodied member in C#? A shorthand for writing simple properties or methods using =>.
- How do you initialize a dictionary in C#? var dict = new Dictionary<int, string> { {1, "One"}, {2, "Two"} };
- What is the nameof operator used for? It returns the string representation of a variable, method, or property name.
- What is the difference between static and instance methods? Static methods belong to the class, whereas instance methods require an object.
- What is the difference between pass-by-value and pass-by-reference? Pass-by-value copies the data, whereas pass-by-reference passes the memory location.
- What is a partial class? A class definition that is split across multiple files.
- What is the difference between async and await? async marks a method as asynchronous, and await pauses execution until the awaited task completes.
- What is the difference between Task and ValueTask? ValueTask is more efficient for short-lived async operations.
- What is a thread pool in .NET? A managed pool of worker threads that execute tasks efficiently.
- How do you create a background worker in .NET? Using Task.Run(() => { }); or BackgroundWorker class.
- How do you use dependency injection in ASP.NET Core? By configuring services in Startup.cs with AddTransient, AddScoped, or AddSingleton.
- What is the purpose of IServiceCollection in .NET? It registers dependencies for dependency injection.
- What is the difference between Transient, Scoped, and Singleton in dependency injection? Transient creates a new instance each time, Scoped creates one per request, and Singleton creates one for the application lifetime.
- How do you define an interface in C#? interface IMyInterface { void Method(); }
- What is the purpose of a constructor? It initializes an object when an instance of a class is created.
- What is a destructor in C#? A special method (~ClassName) that runs when an object is garbage collected.
- What is garbage collection in .NET? Automatic memory management that reclaims unused objects.
- What is a weak reference? A reference to an object that allows garbage collection to reclaim it.
- What is an event in C#? A way to notify subscribers when something occurs, using delegates.
- What is covariance and contravariance? Covariance allows returning derived types, and contravariance allows passing base types.
- How do you perform file I/O in C#? Using File.ReadAllText(), File.WriteAllText(), or FileStream.
- What is serialization? The process of converting an object to a format that can be stored or transmitted.
- What is the difference between JSON and XML serialization? JSON is lightweight and widely used, while XML supports hierarchical data with schemas.
- How do you deserialize a JSON string into an object? Using JsonSerializer.Deserialize<T>(jsonString);
- What is reflection in C#? The ability to inspect and modify metadata at runtime.
- What is the difference between Assembly.Load and Assembly.LoadFile? Load loads from the application domain, while LoadFile loads from a specific path.
- What is an attribute in C#? Metadata that provides additional information about a class, method, or property.
- What is the purpose of the [Obsolete] attribute? It marks a method or class as deprecated.
- What is the difference between Debug and Release modes? Debug includes extra debugging information, while Release optimizes performance.
- What is a GUID in C#? A globally unique identifier, represented as a 128-bit number.
- What is the purpose of the Stopwatch class? To measure elapsed time for performance testing.
- How do you create a custom exception in C#? By inheriting from Exception and defining a new class.
- What is a memory leak in .NET? A situation where objects are not properly released from memory.
- How do you prevent memory leaks in C#? By properly disposing of objects, avoiding event handler leaks, and using weak references.
- What is the IDisposable interface? It defines a Dispose method for releasing unmanaged resources.
- How do you implement the IDisposable pattern? By implementing IDisposable and disposing of resources in the Dispose method.
- What is the difference between Dispose and Finalize? Dispose is called explicitly, while Finalize is called by the garbage collector.
- How do you use the lock statement in C#? lock(obj) { /* critical section */ }
- What is the purpose of the Monitor class? It provides advanced thread synchronization features.
- What is the difference between a Mutex and a Semaphore? Mutex allows only one thread, while Semaphore allows a limited number.
- How do you handle deadlocks in C#? By avoiding circular locks and using timeout-based locking.
- What is a race condition? A situation where multiple threads access shared data unpredictably.
- How do you implement thread safety in C#? By using locks, mutexes, and concurrent collections.
- What is an atomic operation? An operation that completes without interference from other threads.
- What is the difference between Thread and Task? Thread is a low-level unit of execution, whereas Task is a high-level abstraction for parallelism.
- How do you use Parallel.ForEach in C#? Parallel.ForEach(collection, item => { /* logic */ });
- What is the difference between PLINQ and LINQ? PLINQ is parallelized for better performance on multicore processors.
- How do you unit test a method in C#? Using xUnit, NUnit, or MSTest frameworks.
- What is a mock in unit testing? A fake implementation of a dependency used for testing.
- What is dependency inversion? A principle that high-level modules should not depend on low-level modules.
- How do you inject dependencies in a constructor? By passing required dependencies via the constructor.
- How do you create an extension method in C#? Define a static method in a static class with 'this' as the first parameter.
- What is the difference between Select and Where in LINQ? Select projects data, while Where filters data.
- How do you perform a left join in LINQ? Using GroupJoin with DefaultIfEmpty.
- How do you execute raw SQL in Entity Framework? context.Database.ExecuteSqlRaw("SQL_QUERY");
- What is lazy loading in Entity Framework? Entities are loaded only when accessed, improving performance.
- How do you enable eager loading in Entity Framework? Using Include() to load related entities upfront.
- How do you implement CQRS in .NET? By separating queries and commands into different models.
- What is MediatR? A library that implements the mediator pattern for CQRS in .NET.
- How do you register middleware in ASP.NET Core? Using app.UseMiddleware<CustomMiddleware>();
- What is a filter in ASP.NET Core? A way to execute code before or after a request, such as authorization filters.
- What is the difference between an API controller and an MVC controller? API controllers return JSON by default, whereas MVC controllers return views.
- How do you implement WebSockets in .NET? Using SignalR for real-time communication.
- Front Back
- What is the difference between IEnumerable<T> and List<T>? IEnumerable<T> is an interface that supports iteration, whereas List<T> is a concrete implementation with additional functionality.
- What is the difference between == and Equals() when comparing strings in C#? == checks reference equality unless overloaded, while Equals() checks value equality.
- What is string interning in C#? A mechanism where identical string literals are stored in a single memory location to optimize performance.
- How do you reverse a string in C#? new string(myString.Reverse().ToArray());
- How do you remove all whitespace from a string in C#? string.Replace(" ", ""); or Regex.Replace(string, "\s", "");
- What is the difference between StringBuilder and string in C#? StringBuilder is mutable and more efficient for frequent modifications, whereas string is immutable.
- How do you convert a string to a char array? string.ToCharArray();
- How do you join an array of strings into a single string? string.Join(",", myArray);
- What is the difference between a deep copy and a shallow copy? A shallow copy copies references, while a deep copy creates new independent objects.
- What is a dictionary in C#? A collection of key-value pairs that allows fast lookups.
- How do you check if a key exists in a Dictionary<TKey, TValue>? dictionary.ContainsKey(key);
- How do you retrieve a value from a dictionary safely? dictionary.TryGetValue(key, out value);
- What is the difference between HashSet<T> and List<T>? HashSet<T> does not allow duplicate values and provides fast lookups, while List<T> allows duplicates.
- How do you convert a List<T> to an array? list.ToArray();
- How do you convert an array to a List<T>? array.ToList();
- What is a nullable value type in C#? A value type that can also store null, declared using int? or Nullable<int>.
- What is the ??= operator in C#? It assigns a value only if the variable is null.
- What is a jagged array? An array of arrays where each inner array can have different lengths.
- What is a multidimensional array? An array with multiple dimensions, declared as int[,].
- How do you sort an array in C#? Array.Sort(myArray);
- How do you shuffle a list randomly in C#? Using LINQ: myList.OrderBy(x => Guid.NewGuid()).ToList();
- What is the difference between a property and a field? A field stores data directly, while a property provides controlled access to a field.
- What is an indexer in C#? A special property that allows an object to be accessed like an array.
- How do you declare a readonly auto-implemented property? public string Name { get; } = "Default";
- What is method overloading? Defining multiple methods with the same name but different parameter lists.
- What is method overriding? Redefining a method in a derived class using the override keyword.
- What is the difference between virtual and abstract methods? Virtual methods have a base implementation but can be overridden, while abstract methods must be implemented in derived classes.
- How do you prevent a method from being overridden? Using the sealed keyword on an override method.
- What is polymorphism in C#? The ability to treat derived class objects as instances of a base class.
- What is the purpose of the base keyword? It allows access to members of a base class from a derived class.
- What is an explicit interface implementation? A way to implement an interface method in a way that hides it from the public API of the class.
- What is the difference between dynamic and object in C#? object requires casting for specific types, while dynamic allows operations without compile-time type checking.
- How do you check the type of an object at runtime? Using obj.GetType() or obj is TypeName.
- What is the difference between a synchronous and an asynchronous method? Synchronous methods block execution, while asynchronous methods return immediately and execute later.
- What does ConfigureAwait(false) do in async programming? It prevents context capture, improving performance in libraries.
- What is the purpose of the CancellationToken in async programming? It allows canceling asynchronous operations gracefully.
- How do you handle a timeout in an async method? Using Task.WhenAny(task, Task.Delay(timeout));
- Front Back
- What is the difference between a stack and a heap in C#? The stack stores value types and method calls, while the heap stores reference types and objects.
- What is the purpose of the `readonly` modifier in C#? It ensures that a field can only be assigned in a constructor or declaration.
- What is the difference between `const` and `readonly` in C#? `const` values are compile-time constants, while `readonly` values are set at runtime but cannot be changed afterward.
- How do you perform string concatenation efficiently in C#? Using `StringBuilder` for large operations or `$"interpolated strings"` for small operations.
- What is a `params` array in C#? A parameter that allows passing a variable number of arguments to a method.
- How do you prevent a class from being inherited? By marking it with the `sealed` keyword.
- What is the `default` keyword used for in C#? It returns the default value of a type (`0` for numbers, `null` for reference types, etc.).
- How do you specify a default parameter value in a method? By assigning a value in the parameter list: `void MyMethod(int x = 10)`.
- How do you swap two variables in C# without using a temporary variable? Using tuple deconstruction: `(a, b) = (b, a);`
- What is a `ref` return in C#? A method that returns a reference to a variable instead of a value copy.
- How do you declare a nullable value type explicitly? Using `int? x = null;` or `Nullable<int> x = null;`
- How do you force garbage collection in C#? Calling `GC.Collect()`, though it is generally discouraged.
- What is an enumeration (`enum`) in C#? A set of named integer constants defined using the `enum` keyword.
- What is the difference between `is` and `as` operators in C#? `is` checks type compatibility, while `as` attempts a safe cast, returning `null` if the cast fails.
- What is the difference between `throw` and `throw ex` in C#? `throw` preserves the original stack trace, while `throw ex` resets it.
- How do you create an anonymous type in C#? Using `var obj = new { Name = "John", Age = 30 };`
- What is a primary constructor in C#? A feature that allows constructor parameters to be declared directly in a class declaration (C# 12+).
- What is the difference between `break` and `continue` in loops? `break` exits the loop, while `continue` skips the current iteration and moves to the next one.
- What is a local function in C#? A function defined inside another method, useful for encapsulating logic within a method.
- How do you declare a delegate in C#? Using `delegate int MyDelegate(int x);`
- What is the difference between `Func<T>` and `Action<T>`? `Func<T>` returns a value, while `Action<T>` does not return anything.
- What is the `lock` keyword used for? It prevents multiple threads from accessing the same code section simultaneously.
- How do you implement an explicit interface method? By defining the method with the interface name: `void IMyInterface.Method() { }`
- What is the `nameof` operator used for? It returns the name of a variable, method, or property as a string.
- How do you declare a constant expression in C#? Using `const`: `const double Pi = 3.14159;`
- What is the difference between `dynamic` and `var`? `var` is strongly typed at compile time, while `dynamic` defers type checking until runtime.
- How do you declare an event in C#? Using `public event EventHandler MyEvent;`
- What is a static constructor in C#? A constructor that runs once per type to initialize static fields.
- How do you prevent a method from being overridden in C#? By marking it with `sealed override`.
- What is the difference between `abstract` and `virtual` methods? `abstract` methods must be overridden, while `virtual` methods have a default implementation but can be overridden.
- How do you implement a singleton in C#? By defining a private constructor and a static instance: `public static readonly MyClass Instance = new MyClass();`
- What is an auto-property initializer? A way to set default values for properties at declaration: `public string Name { get; set; } = "Default";`
- How do you get the length of an array in C#? Using `array.Length`.
- What is a tuple in C#? A lightweight data structure that holds multiple values: `(int, string) tuple = (1, "Hello");`
- What is the difference between `out` and `ref` parameters? `out` does not require initialization before passing, while `ref` does.
- How do you check if a string starts or ends with a specific value? Using `string.StartsWith()` or `string.EndsWith()`.
- What is the difference between `ArrayList` and `List<T>`? `ArrayList` holds objects and requires casting, while `List<T>` is type-safe.
- What is a partial method? A method declared in a partial class that may or may not have an implementation.
- What is the difference between `Decimal`, `Double`, and `Float` in C#? `Decimal` is more precise for financial calculations, `Double` is used for general floating-point math, and `Float` has lower precision.
- How do you compare two objects in C#? Using `Equals()` for value comparison or `ReferenceEquals()` for reference comparison.
- What is a collection initializer in C#? A shorthand way to initialize collections: `var list = new List<int> { 1, 2, 3 };`
- How do you convert a string to lowercase or uppercase? Using `string.ToLower()` or `string.ToUpper()`.
- How do you make a method asynchronous? By marking it with `async` and returning `Task` or `Task<T>`.
- How do you read a file line by line in C#? Using `File.ReadLines("filename.txt")`.
- What is an operator overload? A way to define custom behavior for operators like `+` in a class.
- How do you check if a dictionary contains a key? Using `dictionary.ContainsKey(key)`.
- How do you get all keys from a dictionary? Using `dictionary.Keys`.
- How do you create a deep copy of an object? By serializing and deserializing it using `JsonSerializer`.
- How do you filter a list using LINQ? Using `Where()`: `list.Where(x => x > 10);`
- What is a predicate in C#? A function that returns a boolean, often used in filtering: `Predicate<int> isEven = x => x % 2 == 0;`
- How do you remove duplicates from a list in C#? Using `list.Distinct().ToList();`
- What is the difference between `ToList()` and `AsEnumerable()`? `ToList()` forces immediate execution and creates a new list, while `AsEnumerable()` defers execution.
- What is a circular reference in C#? When two objects reference each other, preventing garbage collection.
- How do you avoid memory leaks in event handlers? By unsubscribing using `-= EventHandler;`
- How do you create a JSON object in C#? Using `JsonSerializer.Serialize(object)`.
- How do you deserialize JSON into a dictionary? Using `JsonSerializer.Deserialize<Dictionary<string, object>>(json);`
- How do you perform a case-insensitive string comparison? Using `string.Equals(a, b, StringComparison.OrdinalIgnoreCase)`.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement