문제상황:
C#으로 개발을 진행하던 중, 사용자가 ShoppingCart 객체를 생성하고, 이 객체의 AddProduct 메서드를 호출하여 제품을 추가하려고 시도했습니다. 그러나 다음과 같은 코드에서 에러가 발생했습니다.
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
public class ShoppingCart
{
private List<Product> _products;
public void AddProduct(Product product)
{
_products.Add(product); // 에러가 발생한 부분
}
public decimal CalculateTotalPrice()
{
return _products.Sum(p => p.Price);
}
}
이 코드는 상품을 나타내는 Product 클래스와 장바구니를 나타내는 ShoppingCart 클래스가 포함되어 있습니다. 에러는 ShoppingCart의 AddProduct 메서드에서 발생했습니다.
에러로그 내용:
System.NullReferenceException: Object reference not set to an instance of an object.
해결방법:
에러가 수정된 코드와 수정된 부분에 대한 주석은 다음과 같습니다.
public class ShoppingCart
{
private List<Product> _products;
public ShoppingCart()
{
_products = new List<Product>(); // 수정된 부분: _products 리스트를 초기화
}
public void AddProduct(Product product)
{
_products.Add(product);
}
public decimal CalculateTotalPrice()
{
return _products.Sum(p => p.Price);
}
}
원인분석:
이 에러는 _products 리스트에 인스턴스가 할당되지 않았기 때문에 발생했습니다. 따라서, NullReferenceException이 발생하며 객체 참조가 인스턴스를 참조하도록 설정되지 않았다는 내용의 에러 메시지가 출력되었습니다. 이 문제를 해결하기 위해, ShoppingCart 클래스의 생성자에서 _products 리스트를 초기화해야 합니다.
참고링크:
System.NullReferenceException 공식문서
[NullReferenceException Class (System)
The exception that is thrown when there is an attempt to dereference a null object reference.
learn.microsoft.com](https://docs.microsoft.com/en-us/dotnet/api/system.nullreferenceexception?view=net-6.0)
728x90