Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Cast Entire Array?

Tags:

arrays

c#

casting

I see this Array.ConvertAll method, but it requires a Converter as an argument. I don't see why I need a converter, when I've already defined an implicit one in my class:

    public static implicit operator Vec2(PointF p)
    {
        return new Vec2(p.X, p.Y);
    }

I'm trying to cast an array of PointFs to an array of Vec2s. Is there a nice way to do this? Or should I just suck it up and write (another) converter or loop over the elements?

like image 642
mpen Avatar asked Jan 14 '10 22:01

mpen


People also ask

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

What do you mean by C?

" " C is a computer programming language. That means that you can use C to create lists of instructions for a computer to follow. C is one of thousands of programming languages currently in use.

What language is C written in?

It was based on CPL (Combined Programming Language), which had been first condensed into the B programming language—a stripped-down computer programming language—created in 1969–70 by Ken Thompson, an American computer scientist and a colleague of Ritchie.

Is C still used in 2020?

C/C++ is still powering the world despite number of new high level programming languages. Most of the major software applications including Adobe, Google, Mozilla, Oracle are all written in C/C++. There is a complete article on list of best applications written in C/C++.


2 Answers

The proposed LINQ solution using Cast/'Select' is fine, but since you know you are working with an array here, using ConvertAll is rather more efficienct, and just as simple.

var newArray = Array.ConvertAll(array, item => (NewType)item);

Using ConvertAll means
a) the array is only iterated over once,
b) the operation is more optimised for arrays (does not use IEnumerator<T>).

Don't let the Converter<TInput, TOutput> type confuse you - it is just a simple delegate, and thus you can pass a lambda expression for it, as shown above.

like image 127
Noldorin Avatar answered Oct 06 '22 03:10

Noldorin


As an update to this old question, you can now do:

myArray.Cast<Vec2>().ToArray();

where myArray contains the source objects, and Vec2 is the type you want to cast to.

like image 41
Ravi Avatar answered Oct 06 '22 03:10

Ravi