C# Structs with Functions


This entry is part 6 of 8 in the series C# Complex Types

First, let’s review what a struct is. The struct (short for structure) is just that. That is, structs are data structures composed of several pieces of data, possibly of different types. They enable you to define your own types of variables based on this structure.

A struct is a value type, whereas a class is a reference type. Because a struct is a value type, each instance does not require instantiation of an object on the heap. This is more efficient when you’re creating many instances of a type. A struct does not support inheritance (other than implicitly deriving from object, or more precisely, System.ValueType).

Below in the code there is an example of a struct called Customer. Here we are using a lambda expression.

using System;
namespace StructFunctions
{
    struct Customer
    {  
       public string firstName, lastName;
       public int birthYear;
       public string Name() => firstName + " " + lastName;  // lamda
    }  // Name() has direct access to firstName and lastName
    class Program
    {
        static void Main(string[] args)
        {
            Customer myCustomer;
            myCustomer.firstName = "Sam";
            myCustomer.lastName = "Smith";
            myCustomer.birthYear = 1960;
            Console.WriteLine($"{myCustomer.Name()} was born in {myCustomer.birthYear}.");
           // Output: Sam Smith was born in 1960.
        }
    } 
}
Series Navigation<< C# Structs IntroductionC# Date and Time >>