HomeAbout Me

C# Basic Concepts

By Daniel Nguyen
Published in WPF - CSharp
July 17, 2024
3 min read
C# Basic Concepts

What is C#?

C# (pronounced “C-sharp”) is a modern, object-oriented programming language developed by Microsoft as part of its .NET initiative

What are the main features of C#?

  1. Object-Oriented Programming (OOP):

C# is built around the principles of object-oriented programming, including classes, inheritance, polymorphism, and encapsulation.

  1. Type Safety:

Ensures that all operations are type-checked at compile time, reducing runtime errors and enhancing code reliability.

  1. Garbage Collection:

Automatic memory management through garbage collection, which helps in efficiently managing memory and preventing memory leaks.

  1. Exception Handling:

Structured exception handling with try, catch, finally, and throw keywords to gracefully handle runtime errors.

  1. Language Integrated Query (LINQ):

Provides a powerful, integrated query syntax for querying collections, databases, XML, and more, making data manipulation more intuitive and readable.

  1. Asynchronous Programming:

async and await keywords simplify asynchronous programming, allowing developers to write more responsive and scalable applications.

Explain the difference between value types and reference types in C#.

In C#, the distinction between value types and reference types is fundamental to understanding how data is stored and managed in memory. Here’s a detailed explanation of the differences:

Value Types

  1. Memory Allocation:
  • Value types are typically allocated on the stack.
  • Each variable of a value type has its own copy of the data.
  1. Examples:
  • Primitive types: int, double, bool, char, etc.
  • Structs: Custom structures defined using the struct keyword.
  • Enumerations: Defined using the enum keyword.
  1. Lifetime:
  • The lifetime of a value type is tied to the scope in which it is declared. When the scope ends, the value type is removed from the stack.
  1. Assignment:

When you assign one value type to another, a copy of the data is made. Modifications to one variable do not affect the other.

int x = 10;
int y = x; // y gets a copy of x
y = 20;
// x is still 10

Reference Types

  1. Memory Allocation:
  • Reference types are allocated on the heap.
  • A variable of a reference type stores a reference (or address) to the actual data on the heap.
  1. Examples:
  • Classes: Defined using the class keyword.
  • Arrays: Any array type (e.g., int[], string[]).
  • Delegates: Types that refer to methods.
  • Strings: The string type in C#.
  1. Lifetime:
  • The lifetime of a reference type is managed by the .NET garbage collector. When there are no references to an object, the garbage collector can reclaim the memory.
  1. Assignment:
  • When you assign one reference type to another, only the reference is copied, not the actual data. Both variables then refer to the same object on the heap. Changes to one variable affect the other.
class MyClass
{
public int Value;
}
MyClass obj1 = new MyClass();
obj1.Value = 10;
MyClass obj2 = obj1; // obj2 references the same object as obj1
obj2.Value = 20;
// obj1.Value is now 20, because obj1 and obj2 refer to the same object

What are namespaces in C#?

Namespaces in C# are used to organize code and prevent naming conflicts by grouping related classes, interfaces, enums, structs, and delegates under a unique name. Here are the main features and benefits of using namespaces in C#

Key Features of Namespaces:

  1. Organization:
  • Namespaces help organize code by grouping related elements together. This makes the codebase easier to navigate and maintain.
  1. Avoiding Naming Conflicts:
  • By encapsulating classes and other types within namespaces, you can prevent naming conflicts that might arise if multiple libraries or parts of your code use the same names for different purposes.
  1. Hierarchical Structure:
  • Namespaces can be nested, allowing for a hierarchical organization. This further refines the organization and grouping of related types.
  1. Code Readability:
  • Namespaces improve code readability by providing a clear context for where classes and other types are defined.

Defining and Using Namespaces:

  • Defining a Namespace:
namespace MyApplication.Utilities
{
public class Logger
{
public void Log(string message)
{
// Implementation here
}
}
}
  • Using a Namespace:
using MyApplication.Utilities;
class Program
{
static void Main()
{
Logger logger = new Logger();
logger.Log("Hello, World!");
}
}

Example of Nested Namespaces:

namespace MyApplication
{
namespace Data
{
public class Database
{
// Implementation here
}
}
namespace Services
{
public class AuthenticationService
{
// Implementation here
}
}
}

Aliases and Fully Qualified Names:

  • Using Aliases:
using Auth = MyApplication.Services.AuthenticationService;
class Program
{
static void Main()
{
Auth authService = new Auth();
// Use authService here
}
}
  • Fully Qualified Names:
class Program
{
static void Main()
{
MyApplication.Services.AuthenticationService authService = new MyApplication.Services.AuthenticationService();
// Use authService here
}
}

What is a nullable type in C#?

In C#, a nullable type is a value type that can also represent null, in addition to its normal range of values. This is useful for value types, such as int, double, bool, etc., which by default cannot be null. Nullable types are particularly useful in database interactions, form inputs, and scenarios where a value might be optional or undefined.

Defining Nullable Types

  • Using Nullable

  • Using the shorthand T?:

int? nullableInt = null;

Nullable types have two main properties:

  • HasValue: Indicates whether the variable contains a non-null value.
  • Value: Retrieves the value if HasValue is true; otherwise, it throws an InvalidOperationException.

Example Usage

int? nullableInt = 5;
if (nullableInt.HasValue)
{
Console.WriteLine($"Value: {nullableInt.Value}");
}
else
{
Console.WriteLine("Value is null");
}
nullableInt = null;
if (!nullableInt.HasValue)
{
Console.WriteLine("Value is null");
}

Null-Coalescing Operator

The null-coalescing operator (??) provides a convenient way to specify a default value if the nullable type is null:

int? nullableInt = null;
int value = nullableInt ?? 0; // value will be 0 if nullableInt is null

Null-Conditional Operator

The null-conditional operator (?.) allows you to safely access members and properties of nullable types without needing to check for null explicitly:

int? nullableInt = null;
int length = nullableInt?.ToString().Length ?? 0; // length will be 0 if nullableInt is null

Tags

#Interview

Share

Previous Article
Bioluminescence
Next Article
WPF Basic Concepts

Table Of Contents

1
What is C#?
2
What are the main features of C#?
3
Explain the difference between value types and reference types in C#.
4
What are namespaces in C#?
5
What is a nullable type in C#?

Related Posts

C# Miscellaneous
August 14, 2024
2 min
© 2025, All Rights Reserved.
Powered By

Quick Links

About Me

Legal Stuff

Social Media