C# Object Examples
C# Basic
C# Data Type
C# OOP
C# IO
C# Graphics & UI
C# Advanced
In C#, you can convert an object to a byte array using serialization, deserialize a byte array to an object, get a list of classes in a namespace using reflection, and create a generic list of anonymous class using the Enumerable.Select
method.
using System.IO; using System.Runtime.Serialization.Formatters.Binary; object obj = new object(); BinaryFormatter formatter = new BinaryFormatter(); using (MemoryStream stream = new MemoryStream()) { formatter.Serialize(stream, obj); byte[] byteArray = stream.ToArray(); }
In this example, the BinaryFormatter
class is used to serialize the obj
variable to a MemoryStream
. The ToArray
method is called on the MemoryStream
to convert it to a byte array.
using System.IO; using System.Runtime.Serialization.Formatters.Binary; byte[] byteArray = new byte[] { 1, 2, 3 }; BinaryFormatter formatter = new BinaryFormatter(); using (MemoryStream stream = new MemoryStream(byteArray)) { object obj = formatter.Deserialize(stream); }
In this example, the BinaryFormatter
class is used to deserialize the byteArray
to an object. The Deserialize
method is called on the BinaryFormatter
with a MemoryStream
containing the byte array.
using System.Reflection; using System.Linq; IEnumerable<Type> typesInNamespace = Assembly.GetExecutingAssembly().GetTypes() .Where(t => String.Equals(t.Namespace, "MyNamespace", StringComparison.Ordinal));
In this example, the Assembly.GetExecutingAssembly
method is called to get the assembly of the current executing code. The GetTypes
method is called on the assembly to get all types in the assembly. The Where
method is used to filter the types by namespace. The resulting IEnumerable<Type>
contains all types in the specified namespace.
var anonymousList = myList.Select(x => new { Prop1 = x.Prop1, Prop2 = x.Prop2 }).ToList();
In this example, the myList
variable is a list of objects with Prop1
and Prop2
properties. The Select
method is used to create an anonymous object for each object in the list with only Prop1
and Prop2
properties. The ToList
method is called on the resulting IEnumerable
to create a generic list of anonymous class.
Creating and using objects in C#
In C#, objects are instances of classes, and they encapsulate data and behavior. Here's a basic example:
// Class definition public class Person { // Properties public string Name { get; set; } public int Age { get; set; } // Method public void DisplayInfo() { Console.WriteLine($"Name: {Name}, Age: {Age}"); } } // Creating and using objects Person person1 = new Person(); person1.Name = "John"; person1.Age = 25; person1.DisplayInfo();
Instantiating objects in C#
Objects are instantiated using the new
keyword. For example:
Person person2 = new Person();
C# constructor and object initialization
Constructors are special methods used for object initialization. Example:
public class Person { public Person(string name, int age) { Name = name; Age = age; } } // Usage Person person3 = new Person("Alice", 30);
C# object inheritance
Inheritance allows a class to inherit properties and methods from another class.
public class Student : Person { public string StudentId { get; set; } } // Usage Student student = new Student("Bob", 22);
C# object polymorphism
Polymorphism allows objects of different types to be treated as objects of a common base type.
// Polymorphic method public void DisplayPersonInfo(Person person) { person.DisplayInfo(); } // Usage DisplayPersonInfo(person1); DisplayPersonInfo(student);
Abstract classes and interfaces in C#
Abstract classes and interfaces provide a blueprint for other classes.
public abstract class Shape { public abstract double CalculateArea(); } public interface IDrawable { void Draw(); }
C# object casting and type conversion
Casting allows you to convert objects from one type to another.
object obj = "Hello"; string str = (string)obj;
C# object serialization and deserialization
Serialization involves converting an object to a stream of bytes, and deserialization is the reverse process.
// Serialization string serializedData = JsonConvert.SerializeObject(person1); // Deserialization Person deserializedPerson = JsonConvert.DeserializeObject<Person>(serializedData);
C# object immutability
Immutability ensures that an object's state cannot be changed after creation.
public class ImmutablePerson { public string Name { get; } public int Age { get; } public ImmutablePerson(string name, int age) { Name = name; Age = age; } }
Reflection and dynamic objects in C#
Reflection allows you to inspect and interact with types dynamically.
Type type = typeof(Person); PropertyInfo[] properties = type.GetProperties();