C#
210520 C#_객체생성, 삭제
S_pot
2021. 5. 20. 14:08
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _210520_002
{
class Smart
{
public int Total; // Smart class의 멤버
}
class Program
{
static void Main(string[] args)
{
Smart sNum = new Smart(); // 1번 객체생성
sNum.Total = 21;
Console.WriteLine($"우리반 인원 : {sNum?.Total}"); // ?: 은 해당객체가 null이면 null을 반환하고 그렇지 않으면 뒤에 지정된 멤버를 반환
Console.WriteLine("우리반 인원 : {0}", sNum?.Total);
sNum = null; // 1번 객체삭제
Console.WriteLine($"우리반 인원 : {sNum?.Total}");
Console.WriteLine("우리반 인원 : {0}", sNum?.Total);
sNum = new Smart(); // 2번 객체생성
sNum.Total = 21;
Console.WriteLine($"우리반 인원 : {sNum?.Total}");
Console.WriteLine("우리반 인원 : {0}", sNum?.Total);
}
}
}
출력값
추가코드
static void Main(string[] args)
{
string T = "지옥으로 키티";
Console.WriteLine(T);
Console.WriteLine(T.Length);
T = null;
Console.WriteLine($"[{T}]");
Console.WriteLine($"[{T.Length}]"); // 객체가 없기때문에 Length가 적용되지 않는다.
Console.WriteLine($"[{T?.Length}]"); // ?를 사용했기 때문에 null이 적용된다.
}