C# Structs with Functions


Structs & Structs with Functions

namespace StructFunctions {
    struct Customer  {  // defined in the namespace
        public string firstName, lastName;
        public int birthYear;
        public string Name() => firstName + " " + lastName;
    }  // 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: Jose Reyes was born in 1960.
            Console.ReadKey(); }
    } // structs are value types but classes are reference types
}

Leave a comment

Your email address will not be published. Required fields are marked *