नोट
इस पृष्ठ तक पहुंच के लिए प्राधिकरण की आवश्यकता होती है। आप साइन इन करने या निर्देशिकाएँ बदलने का प्रयास कर सकते हैं।
इस पृष्ठ तक पहुंच के लिए प्राधिकरण की आवश्यकता होती है। आप निर्देशिकाएँ बदलने का प्रयास कर सकते हैं।
This tutorial teaches you how to create types in C#. You write small amounts of code, then you compile and run that code. The tutorial contains a series of lessons that explore different kinds of types in C#. These lessons teach you the fundamentals of the C# language.
The preceding tutorials worked with text and numbers. Strings and numbers are simple types: They each store one single value. As your programs grow larger, you need to work with more sophisticated data structures. C# provides different kinds of types you can define when you need data structures with more fields, properties, or behavior. Let's start to explore those types.
In this tutorial, you:
- Create and manipulate tuple types.
- Create record types.
- Learn about struct, class, and interface types.
Prerequisites
You must have one of the following:
- A GitHub account to use GitHub Codespaces. If you don't already have one, you can create a free account at GitHub.com.
- A computer with the following tools installed:
- The .NET 10 SDK.
- Visual Studio Code.
- The C# DevKit.
To use codespaces, you need a GitHub account. If you don't already have one, you can create a free account at GitHub.com.
Tuples
To start a GitHub Codespace with the tutorial environment, open a browser window to the tutorial codespace repository. Select the green Code button, and the Codespaces tab. Then select the + sign to create a new Codespace using this environment. If you completed other tutorials in this series, you can open that codespace instead of creating a new one.
When your codespace loads, create a new file in the tutorials folder named tuples.cs.
Open your new file.
Type or copy the following code into tuples.cs:
var pt = (X: 1, Y: 2); var slope = (double)pt.Y / (double)pt.X; Console.WriteLine($"A line from the origin to the point {pt} has a slope of {slope}.");Run your program by typing the following commands in the integrated terminal window:
cd tutorials dotnet tuples.csTuples are an ordered sequence of values with a fixed length. Each element of a tuple has a type and an optional name.
Tip
As you explore C# (or any programming language), you make mistakes when you write code. The compiler finds those errors and reports them to you. When the output contains error messages, look closely at the example code and your code to see what to fix. You can also ask Copilot to find differences or spot any mistakes. That exercise helps you learn the structure of C# code.
Add the following code after the previous code to modify a tuple member:
pt.X = pt.X + 5; Console.WriteLine($"The point is now at {pt}.");You can also create a new tuple that's a modified copy of the original using a
withexpression. Add the following code after the existing code and typedotnet tuples.csin the terminal window to see the results:var pt2 = pt with { Y = 10 }; Console.WriteLine($"The point 'pt2' is at {pt2}.");The tuple
pt2contains theXvalue ofpt(6), andpt2.Yis 10. Tuples are structural types. In other words, tuple types don't have names likestringorint. A tuple type is defined by the number of members, referred to as arity, and the types of those members. The member names are for convenience. You can assign a tuple to a tuple with the same arity and types even if the members have different names.You can add the following code after the code you already wrote:
var subscript = (A: 0, B: 0); subscript = pt; Console.WriteLine(subscript);Try it by typing
dotnet tuples.csin the terminal window. The variablesubscripthas two members, both of which are integers. Bothsubscriptandptrepresent instances of the same tuple type: a tuple containing twointmembers.Tuples are easy to create: You declare multiple members enclosed in parentheses. All the following declarations define different tuples with different arities and member types.
Add the following code to create new tuple types:
var namedData = (Name: "Morning observation", Temp: 17, Wind: 4); var person = (FirstName: "", LastName: ""); var order = (Product: "guitar picks", style: "triangle", quantity: 500, UnitPrice: 0.10m);Try this change by typing
dotnet tuples.csagain in the terminal window.
While tuples are easy to create, they're limited in their capabilities. Tuple types don't have names, so you can't convey meaning to the set of values. Tuple types can't add behavior. C# has other kinds of types you can create when your type defines behavior.
Create record types
Tuples are great for those times when you want multiple values in the same structure. They're lightweight, and you can declare them as you use them. As your program grows, you might find that you use the same tuple type throughout your code. If your app works in the 2D graph space, the tuples that represent points might be common. When you find this pattern, you can declare a record type that stores those values and provides more capabilities.
Add the following code to declare and use a
recordtype to represent aPoint:public record Point(int X, int Y);The preceding code must be at the bottom of your source file. Type declarations like
recorddeclarations must follow executable statements in a file-based app.Add the following code preceding the
recorddeclaration:Point pt3 = new Point(1, 1); var pt4 = pt3 with { Y = 10 }; Console.WriteLine($"The two points are {pt3} and {pt4}");The
recorddeclaration is a single line of code for thePointtype that stores the valuesXandYin readonly properties. You use the namePointwherever you use that type. Properly named types, likePoint, provide information about how the type is used. The additional code shows how to use awithexpression to create a new point that's a modified copy of the existing point. The linept4 = pt3 with { Y = 10 }says "pt4has the same values aspt3except thatYis assigned to 10." You can add any number of properties to change in a singlewithexpression.The preceding
recorddeclaration is a single line of code that ends in;. You can add behavior to arecordtype by declaring members. A record member can be a function or more data elements. The members of a type are in the type declaration, between{and}characters.Delete the
;and add the following lines of code after therecorddeclaration:{ public double Slope() => (double)Y / (double)X; }Add the following code before the
recorddeclaration, after the line containing thewithexpression:double slopeResult = pt4.Slope(); Console.WriteLine($"The slope of {pt4} is {slopeResult}");Type
dotnet tuples.csin the terminal window to run this version.You added formality to the tuple representing an
XandYvalue. You made it arecordthat defined a named type and included a member to calculate the slope. Arecordtype is a shorthand for arecord class: Aclasstype that includes extra behavior.You can modify the
Pointtype to make it arecord structas well:public record struct Point(int X, int Y)A
record structis astructtype that includes the extra behavior added to allrecordtypes.Try this version by typing
dotnet tuples.csin the terminal window.
Struct, class, and interface types
All concrete named types in C# are either class or struct types, including record types. A class is a reference type. A struct is a value type. Variables of a value type store the contents of the instance inline in memory. In other words, a record struct Point stores two integers: X and Y. Variables of a reference type store a reference, or pointer, to the storage for the instance. In other words, a record class Point stores a reference to a block of memory that holds the values for X and Y.
In practice, that means value types are copied when assigned, but a copy of a class instance is a copy of the reference. That copied reference refers to the same instance of a point, with the same storage for X and Y.
The record modifier instructs the compiler to write several members for you. You can learn more in the article on record types in the fundamentals section.
When you declare a record type, you declare that your type should use a default set of behaviors for equality comparisons, assignment, and copying instances of that type. Records are the best choice when storing related data is the primary responsibility of your type. As you add more behaviors, consider using struct or class types, without the record modifier.
Use struct types for value types when you need more sophisticated behavior, but the primary responsibility is storing values. Use class types to use object-oriented idioms like encapsulation, inheritance, and polymorphism.
You can also define interface types to declare behavioral contracts that different types must implement. Both struct and class types can implement interfaces.
You typically use all these types in larger programs and libraries. Once you install the .NET SDK, you can explore those types using tutorials on classes in the fundamentals section.
You completed the "Create types in C#" tutorial. You can learn more about types in C# in the following articles:
Cleanup resources
GitHub automatically deletes your Codespace after 30 days of inactivity. If you plan to explore more tutorials in this series, you can leave your Codespace provisioned. If you're ready to visit the .NET site to download the .NET SDK, you can delete your Codespace. To delete your Codespace, open a browser window and navigate to your Codespaces. You should see a list of your codespaces in the window. Select the three dots (...) in the entry for the learn tutorial codespace and select delete.