Zum Fußzeileninhalt springen
.NET HILFE

C# Anonymes Objekt (Wie es für Entwickler funktioniert)

Introduction of Anonymous Object

Anonymous types in C# provide a mechanism to encapsulate public read-only properties into a single anonymous type object without explicitly defining a formal class declaration. They are useful for creating single-use data structures. These are compiler-generated types that derive directly from System.Object, encapsulating object properties efficiently and serving as lightweight, immutable data containers. These types are sealed classes where the compiler automatically infers and generates the type name, which remains inaccessible at the source code level. We'll also discover IronPDF as a PDF library for .NET projects.

Key Characteristics

  • Anonymous types have strictly limited capabilities:
  • Properties are automatically implemented as public read-only within an anonymous type's property definition.
  • Users cannot explicitly define methods, events, or other class members like Equals or GetHashCode methods within them.
  • Cannot be initialized with null values, anonymous functions, or pointer types, ensuring the integrity of anonymous types.

Common Use Cases

LINQ Operations

Anonymous data-type objects excel in LINQ query expressions, particularly in select clauses for anonymous-type objects, where they efficiently return specific property subsets from larger objects. This approach optimizes memory usage by creating temporary objects containing only the necessary data.

Temporary Data Grouping

They serve as efficient containers for temporary data structures when creating a formal class would be excessive. This is particularly useful for short-lived data transformations or intermediate calculations.

Property Encapsulation

Anonymous data type provides a clean way to bundle related object properties together using read-only properties. The compiler ensures type safety while maintaining concise syntax for property access.

Syntax and Structure

The creation of anonymous types follows a specific pattern using the var keyword along with the new operator and object initializer syntax. The compiler automatically generates a type name that remains inaccessible at the source code level.

var person = new { FirstName = "Iron", LastName = "Dev", Age = 35 }; // public int age in this anonymous type
var person = new { FirstName = "Iron", LastName = "Dev", Age = 35 }; // public int age in this anonymous type
Private person = New With {
	Key .FirstName = "Iron",
	Key .LastName = "Dev",
	Key .Age = 35
}
$vbLabelText   $csharpLabel

Property Initialization Rules

The compiler enforces strict rules for property initialization in anonymous types. All properties must be initialized during object creation and cannot be assigned null values or pointer types. Once initialized, property values can be accessed using standard dot notation, but they cannot be modified after initialization due to their read-only nature.

Type Inference and Matching

var person1 = new { Name = "Iron", Age = 30 };
var person2 = new { Name = "Dev", Age = 25 };
var person1 = new { Name = "Iron", Age = 30 };
var person2 = new { Name = "Dev", Age = 25 };
Dim person1 = New With {
	Key .Name = "Iron",
	Key .Age = 30
}
Dim person2 = New With {
	Key .Name = "Dev",
	Key .Age = 25
}
$vbLabelText   $csharpLabel

The compiler generates identical type information for anonymous types with matching property names, types, and order. This allows type compatibility between instances to be used in collections or passed as method parameters within the same assembly.

Nested Anonymous Types

Anonymous data types support complex nested structures with anonymous-type object properties. This is helpful for the creation of hierarchical data representations:

var student = new {
    Id = 1,
    PersonalInfo = new {
        Name = "James",
        Contact = new {
            Email = "james@email.com",
            Phone = "123-456-7890"
        }
    },
    Grades = new { Math = 95, Science = 88 }
};
var student = new {
    Id = 1,
    PersonalInfo = new {
        Name = "James",
        Contact = new {
            Email = "james@email.com",
            Phone = "123-456-7890"
        }
    },
    Grades = new { Math = 95, Science = 88 }
};
Dim student = New With {
	Key .Id = 1,
	Key .PersonalInfo = New With {
		Key .Name = "James",
		Key .Contact = New With {
			Key .Email = "james@email.com",
			Key .Phone = "123-456-7890"
		}
	},
	Key .Grades = New With {
		Key .Math = 95,
		Key .Science = 88
	}
}
$vbLabelText   $csharpLabel

Collection Operations

Anonymous types excel in scenarios involving collection manipulation and data transformation:

var items = new[] {
    new { ProductId = 1, Name = "Laptop", Price = 1200.00m },
    new { ProductId = 2, Name = "Mouse", Price = 25.99m },
    new { ProductId = 3, Name = "Keyboard", Price = 45.50m }
};
var items = new[] {
    new { ProductId = 1, Name = "Laptop", Price = 1200.00m },
    new { ProductId = 2, Name = "Mouse", Price = 25.99m },
    new { ProductId = 3, Name = "Keyboard", Price = 45.50m }
};
Dim items = {
	New With {
		Key .ProductId = 1,
		Key .Name = "Laptop",
		Key .Price = 1200.00D
	},
	New With {
		Key .ProductId = 2,
		Key .Name = "Mouse",
		Key .Price = 25.99D
	},
	New With {
		Key .ProductId = 3,
		Key .Name = "Keyboard",
		Key .Price = 45.50D
	}
}
$vbLabelText   $csharpLabel

IronPDF: C# PDF Library

IronPDF is a powerful library for generating, editing, and managing PDF documents in .NET applications. When working with C#, developers often use anonymous objects for lightweight and ad hoc data structures, especially for scenarios where creating an entire class isn't necessary. These anonymous objects can be seamlessly utilized with IronPDF to create PDF documents dynamically. It helps in creating a flexible solution for quick data-to-PDF workflows. Here’s an example to illustrate how IronPDF works with anonymous objects:

Example: Using Anonymous Objects to Populate a PDF

Imagine you have a list of sales data you want to render as a table in a PDF. Instead of creating a formal class, you can use an anonymous object to quickly format the data for rendering.

using IronPdf;
using System;
using System.Linq;

class Program
{
    static void Main()
    {
        // Set your IronPDF license key here
        License.LicenseKey = "Your-Licence-Key";

        // Sample data using anonymous objects
        var salesData = new[]
        {
            new { Product = "Laptop", Quantity = 2, Price = 1200.50 },
            new { Product = "Smartphone", Quantity = 5, Price = 800.00 },
            new { Product = "Headphones", Quantity = 10, Price = 150.75 }
        };

        // Create an HTML string dynamically using the anonymous object data
        var htmlContent = @"
        <html>
        <head><style>table {border-collapse: collapse;} th, td {border: 1px solid black; padding: 5px;}</style></head>
        <body>
        <h1>Sales Report</h1>
        <table>
            <thead>
                <tr>
                    <th>Product</th>
                    <th>Quantity</th>
                    <th>Price</th>
                </tr>
            </thead>
            <tbody>
                " +
            string.Join("", salesData.Select(item =>
                $"<tr><td>{item.Product}</td><td>{item.Quantity}</td><td>{item.Price:C}</td></tr>")) +
            @"
            </tbody>
        </table>
        </body>
        </html>";

        // Generate the PDF
        var renderer = new ChromePdfRenderer();
        var pdf = renderer.RenderHtmlAsPdf(htmlContent);

        // Save the PDF
        pdf.SaveAs("SalesReport.pdf");
        Console.WriteLine("PDF generated successfully!");
    }
}
using IronPdf;
using System;
using System.Linq;

class Program
{
    static void Main()
    {
        // Set your IronPDF license key here
        License.LicenseKey = "Your-Licence-Key";

        // Sample data using anonymous objects
        var salesData = new[]
        {
            new { Product = "Laptop", Quantity = 2, Price = 1200.50 },
            new { Product = "Smartphone", Quantity = 5, Price = 800.00 },
            new { Product = "Headphones", Quantity = 10, Price = 150.75 }
        };

        // Create an HTML string dynamically using the anonymous object data
        var htmlContent = @"
        <html>
        <head><style>table {border-collapse: collapse;} th, td {border: 1px solid black; padding: 5px;}</style></head>
        <body>
        <h1>Sales Report</h1>
        <table>
            <thead>
                <tr>
                    <th>Product</th>
                    <th>Quantity</th>
                    <th>Price</th>
                </tr>
            </thead>
            <tbody>
                " +
            string.Join("", salesData.Select(item =>
                $"<tr><td>{item.Product}</td><td>{item.Quantity}</td><td>{item.Price:C}</td></tr>")) +
            @"
            </tbody>
        </table>
        </body>
        </html>";

        // Generate the PDF
        var renderer = new ChromePdfRenderer();
        var pdf = renderer.RenderHtmlAsPdf(htmlContent);

        // Save the PDF
        pdf.SaveAs("SalesReport.pdf");
        Console.WriteLine("PDF generated successfully!");
    }
}
Imports IronPdf
Imports System
Imports System.Linq

Friend Class Program
	Shared Sub Main()
		' Set your IronPDF license key here
		License.LicenseKey = "Your-Licence-Key"

		' Sample data using anonymous objects
		Dim salesData = {
			New With {
				Key .Product = "Laptop",
				Key .Quantity = 2,
				Key .Price = 1200.50
			},
			New With {
				Key .Product = "Smartphone",
				Key .Quantity = 5,
				Key .Price = 800.00
			},
			New With {
				Key .Product = "Headphones",
				Key .Quantity = 10,
				Key .Price = 150.75
			}
		}

		' Create an HTML string dynamically using the anonymous object data
		Dim htmlContent = "
        <html>
        <head><style>table {border-collapse: collapse;} th, td {border: 1px solid black; padding: 5px;}</style></head>
        <body>
        <h1>Sales Report</h1>
        <table>
            <thead>
                <tr>
                    <th>Product</th>
                    <th>Quantity</th>
                    <th>Price</th>
                </tr>
            </thead>
            <tbody>
                " & String.Join("", salesData.Select(Function(item) $"<tr><td>{item.Product}</td><td>{item.Quantity}</td><td>{item.Price:C}</td></tr>")) & "
            </tbody>
        </table>
        </body>
        </html>"

		' Generate the PDF
		Dim renderer = New ChromePdfRenderer()
		Dim pdf = renderer.RenderHtmlAsPdf(htmlContent)

		' Save the PDF
		pdf.SaveAs("SalesReport.pdf")
		Console.WriteLine("PDF generated successfully!")
	End Sub
End Class
$vbLabelText   $csharpLabel

C# Anonymous Object (How it Works for Developers): Figure 1 - Console output from code example above

Conclusion

C# Anonymous Object (How it Works for Developers): Figure 2 - IronPDF Licensing Page

Anonymous types in C# provide a flexible and efficient way to create temporary data structures without the need for formal class declarations. They are particularly useful when working with LINQ queries, data transformations, and libraries like IronPDF. Combining anonymous types with IronPDF's PDF generation capabilities offers a powerful solution for creating dynamic, data-driven PDFs with minimal code overhead.

IronPDF allows developers to test its features through a free trial, making it easy to explore its capabilities in your .NET applications. Commercial licenses start at $799 and grant access to its full feature set, including high-performance HTML-to-PDF rendering, PDF editing, and security features.

Häufig gestellte Fragen

Was sind anonyme Typen in C#?

Anonyme Typen in C# bieten einen Mechanismus, um öffentliche schreibgeschützte Eigenschaften in einem einzigen anonymen Typobjekt zu kapseln, ohne eine formale Klassendeklaration explizit zu definieren. Sie sind kompilererstellte Typen, die als leichte, unveränderliche Datencontainer verwendet werden.

Wie kann ich einen anonymen Typ in C# erstellen?

Um einen anonymen Typ in C# zu erstellen, verwendet man das var-Schlüsselwort mit dem new-Operator und einer Objektinitialisierersyntax. Der Compiler generiert automatisch den Typnamen und die Struktur basierend auf den angegebenen Eigenschaften.

Wie funktionieren anonyme Typen mit LINQ-Operationen in C#?

Anonyme Typen glänzen in LINQ-Abfrageausdrücken, insbesondere in den select-Klauseln, indem sie effizient spezifische Eigenschaftsuntergruppen aus größeren Objekten zurückgeben und so den Speicherverbrauch optimieren.

Können anonyme Typen in verschachtelten Strukturen verwendet werden?

Ja, anonyme Typen können in verschachtelten Strukturen verwendet werden. Dies ermöglicht die Erstellung hierarchischer Datenrepräsentationen, bei denen Eigenschaften eines anonymen Typs selbst anonyme Typobjekte sein können.

Wie kann ich anonyme Objekte verwenden, um dynamische PDFs zu erstellen?

Anonyme Objekte können Daten schnell zum Rendern in dynamischen PDFs formatieren. Durch die Kombination mit einer PDF-Bibliothek wie IronPDF können Sie effizient PDFs mit minimalem Code erzeugen.

Was sind die Einschränkungen anonymer Typen in C#?

Anonyme Typen sind auf öffentliche, schreibgeschützte Eigenschaften beschränkt und können keine Methoden, Ereignisse oder explizit definierten Klassenmitglieder haben. Sie können auch nicht mit Nullwerten oder Zeigertypen initialisiert werden.

Was sind die häufigsten Anwendungsfälle für anonyme Typen?

Häufige Anwendungsfälle für anonyme Typen umfassen temporäre Datenzusammenfassung, Kapselung von Eigenschaften und Sammlungsoperationen, bei denen die Erstellung einer formalen Klasse überflüssig wäre.

Wie können PDF-Bibliotheken Daten-zu-PDF-Workflows in .NET-Anwendungen verbessern?

PDF-Bibliotheken bieten robuste Werkzeuge für die Erstellung, Bearbeitung und Verwaltung von PDF-Dokumenten innerhalb von .NET-Anwendungen und erleichtern effiziente Daten-zu-PDF-Workflows und verbessern datengesteuerte Lösungen.

Curtis Chau
Technischer Autor

Curtis Chau hat einen Bachelor-Abschluss in Informatik von der Carleton University und ist spezialisiert auf Frontend-Entwicklung mit Expertise in Node.js, TypeScript, JavaScript und React. Leidenschaftlich widmet er sich der Erstellung intuitiver und ästhetisch ansprechender Benutzerschnittstellen und arbeitet gerne mit modernen Frameworks sowie der Erstellung gut strukturierter, optisch ansprechender ...

Weiterlesen