In C#, an anonymous object is an object that is defined without an explicit class or type name. Instead, its properties are defined inline using a special syntax. Anonymous objects are typically used for creating objects with a small number of properties for use in local scope, such as in LINQ queries or when returning data from a method.
Here's an example of how to create an anonymous object in C#:
xxxxxxxxxx
var person = new { Name = "John Smith", Age = 30 };
//You can access the properties of an anonymous object using dot notation:
string name = person.Name; // "John Smith"
int age = person.Age; // 30
Note that anonymous objects are read-only and their properties cannot be modified after they are created. Also, because anonymous objects are implicitly typed, you cannot use them as return types or parameters in method signatures. If you need to define a type with properties that can be used across multiple methods or classes, you should define a custom class or struct instead of using an anonymous object.
xxxxxxxxxx
/*
As the name suggests, an anonymous method is a method without a name.
Anonymous methods in C# can be defined using the delegate keyword
and can be assigned to a variable of delegate type.
*/
//For example, suppose we have a delegate that points to a void method with only one parameter.
delegate void Display(string msg);
static void Main(string[] args)
{
// Make a delegate instance that points to an anonymous method.
Display d2 = delegate(string msg) {
Console.WriteLine();
};
// this function has no name
// If your function contains a single statement, you can remove the delegate keyword, the datatype of the variable, and the curly braces.
/*
Display d2 = msg => Console.WriteLine(msg);
This is ( => ) known as a "fat arrow."
This syntax is called a lambda expression.
*/
Display d = msg => Console.WriteLine(msg);
}