C# .NET

[C#] 간결한 표현식 (expression)

Code GGOON 2022. 7. 3. 00:18
반응형

[기본 문법 구조]

 

member => expression;

 

(예제 1 : 메서드)

using System;

pubbic class Person
{
	private string fname;
    pricate string lname;
    
    public Person(string firstName, string lastName)
    {
    	fname = firstName;
        lname = lastName;
    }
    
    //간결한 표현식 예시
    public override string ToString() => $"{fname} {lname}".Trim();
    public void DisplayName() => Console.WriteLine(ToString());
}


class Example
{
	static void Main()
    {
    	Person person = new Person("Mandy", "Dejesus");
        Console.WriteLine(person);
        person.DisplayName();
     }
 }
 
 // By Microsoft MDSN Document

 

(예제 2 : 생성자)

public class Location
{
	private string locationName;
    
    public Location(string name) => Name = name;
    public string Name
    {
    	get => locationName;
        set => locationName = value;
    }
}

// by Microsoft MSDN Document

 

(예제 3 : 소멸자/종료자)

using System;

public class Destroyer
{
	public override string ToString() => GetType().Name;
    
    ~Destroyer() => Console.WriteLine($"The {ToString()} destructor is executing.");   
}

 

(예제 4 : 인덱서)

using System;
using System.Collections.Generic;

public class Sports
{
	public string[] types = {"Baseball", "Basketball", "Football", "Hockey", 
    "Soccer", "Tennis", "Volleyball"};

	public string this[int i]
	{
		get => types[i];
    	set => types[i] = value;
    }
}

 

[참조] Microsoft MSDN C# Guide Documents

반응형