Christian Frantz
Christian Frantz

Reputation: 253

Add method in a list

I'm trying to add a short value to my indices list, but I'm getting an error that the method has invalid arguments.

    int verticesStart = vertices.Count();
    short vertStart = (short)verticesStart;

Since the indices list is a "short", I cast the variable verticesStart so it is usable.

    indices.Add(vertStart + 0);

This line is where I get the error. Am I not allowed to do any kind of math function in an Add method?

Upvotes: 1

Views: 112

Answers (4)

jason
jason

Reputation: 241641

Since the indices list is a "short"

Therefore, you can only add shorts to indices.

vertStart + 0

The rules of the language specify that short + int has type int. Since vertStart is of type short and 0 is an int literal, vertStart + 0 has type int. Therefore,

indices.Add(vertStart + 0);

is attempting to add an int to a list that you said holds shorts. This is not possible.

Am I not allowed to do any kind of math function in an Add method?

That is not the point. Any expressions are evaluated for their values before they are passed along to the Add method. In your case, you have an expression that evaluates to type int. But if indicies is really a List<short> as you say, then you can't add ints to it. You will have to have a narrowing conversion to short.

indices.Add((short)(vertStart + 0));

Upvotes: 2

Tim S.
Tim S.

Reputation: 56536

Arithmetic in C# is defined for 32-bit and up integer types, not for short. When you do vertStart + 0, the result is an int, that you have to cast back to a short:

indices.Add((short)(vertStart + 0));

(I'm assuming you're not actually adding 0, but some other value. Because adding 0, of course, doesn't change the value.)

Upvotes: 3

Jon
Jon

Reputation: 40032

Using this:

using System;
using System.Collections.Generic;

public class Test
{
    public static void Main()
    {
        List<short> list = new List<short>();
        list.Add(1+1);
    }
}

In C#, the 1 will be int so you need to make sure you add variables of short

Upvotes: -2

Joey
Joey

Reputation: 354476

Arithmetic is always done on at least int. So when you do that addition (why add 0, if I may ask?) you're going to get an int back. You'd have to cast back to short afterwards again.

Upvotes: 0

Related Questions