[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Error:  Cannot implicitly convert type 'T[]' to 'int[]'

Posted on 2012-09-05
15
Medium Priority
?
820 Views
Last Modified: 2012-09-05
I am looking for the outcome to be {2,2,2} instead of {2,2,2,3}, so that I want
assign the values from the array where I got the needed result to a temporary
new array (arrayTemp). I understand it cannot implicitly convert inside my method. However, how is it implicitly converted inside the for?

            foreach (int i in array)
                Console.WriteLine(i); // Print results.


    class Sample
    {
        static Int32[] arrayTemp;

        static void Main()
        {
            Int32 [] array = { 0, 1, 2, 3,};
            MakeAtLeast<int>(array, 2); // Change array to { 2, 2, 2, 3 }
            foreach (int i in array)
                Console.WriteLine(i); // Print results.
            Console.ReadKey(true);
        }


        //T[] list => my own comment: passing by reference
        static void MakeAtLeast<T>(T[] list, T lowest) 
            where T : IComparable<T>
        {
            //using where constraint
            for (int i = 0; i < list.Length; i++)
            {
                if (list[i].CompareTo(lowest) < 0)
                    list[i] = lowest;

                arrayTemp = list;
            }
            
        }
    }

Open in new window

0
Comment
Question by:DistillingExperts
  • 6
  • 5
  • 4
15 Comments
 
LVL 16

Expert Comment

by:ToddBeaulieu
ID: 38368865
The list isn't implicitly converted inside the enumeration. The array supports enumeration regardless of the type. Inside your enumeration you're accessing each element as its correct type, so all is well.

If you want to change your question to "how can I convert the generics array to an Int32 array, we can go down that path, but as it stands, there's no conversion taking place.
0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 38368902
"I am looking for the outcome to be {2,2,2}"

Besides Todd's excellent question, how do you come up with "{2,2,2}"?
0
 

Author Comment

by:DistillingExperts
ID: 38369044
What are you guys are talking about? I have a compile-time error happening here:

arrayTemp = list;

Open in new window


How to fix that?

Besides Todd's excellent question, how do you come up with "{2,2,2}"?

list has it, or am I wrong?
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 38369102
Try this out:
        static Int32[] arrayTemp;

        static void Main()
        {
            Int32[] array = { 0, 1, 2, 3, };
            arrayTemp = MakeAtLeast<int>(array, 2); // Change array to { 2, 2, 2, 3 }
            Console.WriteLine("array:");
            foreach (int i in array)
                Console.WriteLine(i); // Print results.
            Console.WriteLine("arrayTemp:");
            foreach (int i in arrayTemp)
                Console.WriteLine(i); // Print results.
            Console.ReadKey(true);
        }


        //T[] list => my own comment: passing by reference
        static T[] MakeAtLeast<T>(T[] list, T lowest)
            where T : IComparable<T>
        {
            //using where constraint
            for (int i = 0; i < list.Length; i++)
            {
                if (list[i].CompareTo(lowest) < 0)
                    list[i] = lowest;
            }
            return list;
        }

Open in new window

0
 
LVL 16

Expert Comment

by:ToddBeaulieu
ID: 38369150
The sample code looks like an exercise to me, so I wasn't going to try to change too much or second guess the motives. I agree with the idle's post that the method should really be returning the result anyway. Passing by ref like that is probably not the best approach. Not to mention that the assignment in question (that's failing) seems pointless, as the target doesn't appear to be used.

In any case, the one liner to fix the code could be something like this:

arrayTemp = Array.ConvertAll(list, a => Int32.Parse(a.ToString()));

Here, you're using the Array class' built in conversion function, passing in the list as the source and a function that transforms the elements from type T to type Int32. I believe you have to do the conversion at runtime like this. I think it's the only way to make the compiler happy.
0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 38369192
...I'm still trying to figure out what end goal is based on the initial description!  ;)
0
 

Author Comment

by:DistillingExperts
ID: 38369351
@ToddBeaulieu, thanks for the example and explanation, but I must say Idle fixed that in a much simpler way.

Now I understand what this exercise is doing. The name MakeAtLeast is misleading and I changed it to ReplaceNumberLowerThanParameter. However, my other point is to understand how the parameter "caller" managed to be an array while the parameter "receiver" managed to be a T[] list and everything works? I still have some troubles to understand what's behind Generics concepts.
0
 
LVL 16

Expert Comment

by:ToddBeaulieu
ID: 38369377
Ah, but it does NOT take in a list, does it! It takes in an array that you called "list". Nowhere in there is it managing a list. You're enumerating the array in a similar manner as you would with a list because they both support IEnumerable.
0
 

Author Comment

by:DistillingExperts
ID: 38369414
Where am I enumerating it? It is another issue for me to understand. True, it's not a list, but the exercise is not mine  though. I am using it to try to understand Generics.
0
 
LVL 16

Expert Comment

by:ToddBeaulieu
ID: 38369452
foreach
for (int i = 0; i < list.Length; i++)

Both examples of enumerating.
0
 

Author Comment

by:DistillingExperts
ID: 38369510
Why should I see a for as a IEnumerable and not only as a simple for? Still, I don't understand why I send array and receive a T[].
0
 
LVL 16

Expert Comment

by:ToddBeaulieu
ID: 38369642
Just look at how much nicer the foreach is! There's no boundary, incrementing or comparison logic needed. It automatically provides an instance from the collection each time it's executed, so you don't have to fetch the item by index into an explicitly created object.

Generics can be difficult to learn. I think you need to find some more examples and tutorials and ease your way into them. If you're still working on basics like method calls, return types and enumerating, I actually suggest you stick with those basics before worrying about generics. You have too many concepts you're trying to master at once!

In response, though, the second method is a generic. When you pass the array you're specifying <int> which the compiler uses to generate the conversion code for you. I wouldn't use that code example for learning if I were you.
0
 
LVL 86

Accepted Solution

by:
Mike Tomlinson earned 2000 total points
ID: 38369745
"However, my other point is to understand how the parameter "caller" managed to be an array while the parameter "receiver" managed to be a T[] list"

The "T" takes on whatever type you tell it to be, and as Todd mentioned, "list" is simply a variable name which we could just as easily change to "duckFace".

Notice that in your call to MakeAtLeast() you are actually telling it what type is being passed in:

    MakeAtLeast<int>(array, 2);

The part in bold, "<int>", tells MakeAtLeast() that you are passing in type of int and to replace all occurrences of "T" with "int".

You can actually omit the type and call it like this:

    MakeAtLeast(array, 2);

Then MakeAtLeast() will infer (figure out at run-time) what the type of the parameter is for you and do the replacement.

Now, your first parameter to MakeAtLeast() is:

    T[] list

The square brackets "[]" mean array, and the "T" means it will be an array of whatever type is passed.  In this case, a variable of array type "int" was passed in so:

    T[] --> magically becomes --> int[]

...and "int[]" is clearly an array of int, just like the original variable of "array" was.

Does that make sense?
0
 

Author Comment

by:DistillingExperts
ID: 38369911
Now it makes sense. Thank you!

@ToddBeaulieu
No, I am not trying to master too many things. I came from structured language, passing by Java before arriving into C#. I understand enumerates for foreach and how it is easy to use that with Entity Framework or LINQ, for instance. However, it bothers me on the for part of it.

By the way, you also have some refactoring homework to do, given your first solution :-).

Thanks.
0
 

Author Comment

by:DistillingExperts
ID: 38369971
Since noboby said anything, I will do that. Unless proved on the contrary your below statement is false, for is not a enumerating, only foreach:


foreach
for (int i = 0; i < list.Length; i++)

Both examples of enumerating.
0

Featured Post

Prep for the ITIL® Foundation Certification Exam

December’s Course of the Month is now available! Enroll to learn ITIL® Foundation best practices for delivering IT services effectively and efficiently.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
Hello there! As a developer I have modified and refactored the unit tests which was written by fellow developers in the past. On the course, I have gone through various misconceptions and technical challenges when it comes to implementation. I would…
This video teaches viewers about errors in exception handling.
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…
Suggested Courses

831 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question