Error CS0119; class is a type, which is not valid in the given context

Viewed 4086

Upon becoming familiar with C#, I'm getting the following error when unit testing on the line where an assertion is made Assert.IsInstanceTypeOf.

Error CS0119 'Product' is a type, which is not valid in the given context

The matter of creating a type has been performed. What is causing this error to be raised?

UnitTest1.cs

using Microsoft.VisualStudio.TestTools.UnitTesting;
using ProductNamespace;

namespace TestProject2
{
    [TestClass]
    public class TestProduct
    {
        [TestMethod]
        public void TestNewProduct()
        {
            Product mock_product = new Product(4.95);
            Assert.IsInstanceOfType(mock_product, Product);
        }
    }
}

Product.cs

namespace ProductNamespace
{
    public class Product
    {
        private double price;

        public Product(double price)
        {
            this.price = price;
        }
    }
}
2 Answers

It looks like you're trying to use the IsInstanceOfType(object, Type) method. To do that, you need to provide a Type argument, but currently you've just specified the class name directly. That's not a valid C# expression - you need to use the typeof operator to obtain a Type from the class name:

Assert.IsInstanceOfType(mock_product, typeof(Product));

Note that this really isn't a useful test - you're not testing anything about the code, you're essentially asking whether .NET is behaving normally. If the code reaches that line (i.e. if the constructor doesn't throw an exception) then it's bound to pass - because the result of new Xyz is always an Xyz. (There's a slight edge case around COM interfaces, but it's not relevant here.)

Assert.IsInstanceOfType(mock_product, typeof(Product));

Please try the above. As per official documentation, the second parameter should be of Type.

Related