c# deconstruct variable > IT Note

본문 바로가기
사이트 내 전체검색

로그인
회원가입
IT Note

c# deconstruct variable
1

View 2,137  | 작성일2022.02.24 10:37

본문


Deconstructing variable 은 C# 7.0 (2017.02) 에 처음 도입되었습니다. C# 7.0 이전에는 튜플 형식을 반환하는 메서드를 호출 할 때, Tuple 의 immutability , Code readability 등의 이유로 보통 각각의 필드를 변수 할당한 후 사용했습니다.

(string, int, double) QueryCityData(string name)
{
  if (name == "New York City")
  {
    return (name, 8175133, 468.48);
  }
  return ("", 0, 0);
}
var result = QueryCityData("New York City");

var city = result.Item1;
var pop = result.Item2;
var size = result.Item3;
...
하지만 C# 7.0 이후로 deconstructing 을 지원하면서 다음과 같이 바로 반환되는 필드를 선언해 사용하면 됩니다.

var (city, population, area) = QueryCityData("New York City");
이 때 필요하지 않은 필드는 underscore 를 사용하여 무시하면 됩니다.

var (city, population, _) = QueryCityData("New York City");
Deconstruct variable 은 사용자 정의 타입에도 사용 될 수 있으며, 다음과 같이 out parameter 를 갖는 Deconstruct 메서드를 정의해 주면 됩니다.

public struct Human
{
  public string Sex { get; init; }
  public int Age { get; init; }
  public void Deconstruct(out string sex, out int age)
  {
    sex = Sex;
    age = Age;
  }
}
var (sex, age) = new Human { Sex = "male", Age = 15 };
C# 9 에서 소개된 record 와 함께 사용시 별도로 Deconstruct 메서드 정의 없이 처리가 가능합니다.

public record Human(string Sex, int Age);
var (sex, age) = new Human("male", 15);
이 때 당연히 positional parameter 를 통해 만들어지지 않은 property 는 deconstruct 대상에서 제외 됩니다.

public record Human(string Sex, int Age)
{
  public DateTime BirthDay { get; init; }
}
var (sex, age, birthDay) = new Human("male", 15) {
  BirthDay = new DateTime(2000, 1, 1)
}; // error

댓글목록

IT Tip&Tech 목록

게시물 검색

접속자집계

오늘
994
어제
692
최대
6,399
전체
676,026
Copyright © LittleCandle All rights reserved.
문의메일 : littlecandle99@gmail.com
모바일 버전으로 보기