In VB.net, I can write:
If {"red", "blue"}.Contains("blue") Then Return True
and the Contains seems to be from Linq.Enumerable(Of T).
I'm having trouble converting it to C# - when I use an online conversion tool like the one from Developer Fusion, it gives me:
if ({"red", "blue"}.Contains("blue")) return true;
but it doesn't compile, saying it's unable to resolve the symbol Contains which isn't very helpful. I'm sure it's a simple syntax issue, but I'm not sure what you call an example like this.
I don't need to instantiate the array, since I'm just using it to evaluate the expression inline. This seems to be possible in VB.NET. What do you call this - a static array? constant array? anonymous array? some combination of those listed?
I'd like to know how to write this in C#, and also what this is called (I'll update the question title and tags to better reflect what I'm asking when someone can answer that). Thanks!
This would be your direct conversion
if (new []{"red", "blue"}.Contains("blue")) return true;
Oh, it's called an array initializer
Related
In C++ is assumed to be false while all other values are true. I was under the impression that in C# this concept was the same.
I'm trying to convert a char to a bool.
char c = (char)0;
Convert.ToBoolean(c).Dump();
It seems like no matter what char I try to convert I always get an error
Invalid cast from 'Char' to 'Boolean
I understand what I can to to fix this if I write my own custom function, but what I am trying to understand is.
What is the purpose of this method, What Char value converts to Bool?
You stated:
I was under the impression that in C# this concept was the same.
You were mistaken. It isn't. The two languages behave differently in that way, and you simply cannot convert a Char to a Boolean.
The documentation makes it clear that the method always fails:
Calling this method always throws InvalidCastException.
and...
Return Value
Type: System.Boolean
This conversion is not supported. No value is returned.
As evidenced by the source for Char.ToBoolean():
[__DynamicallyInvokable]
bool IConvertible.ToBoolean(IFormatProvider provider)
{
object[] values = new object[] { "Char", "Boolean" };
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", values));
}
As the Char class inherits from IConvertible, it is required to provide the overload. But since this conversion is not possible, an exception is always returned.
Just to show how it can be done with unsafe keyword (similar to c++). Don't use this..
char c = (char)0;
unsafe{
bool b = *((bool *)&c);
}
What is the purpose of this method...?
From the .NET 2.0 documentation:
This method is reserved for future use.
Perhaps they were considering implementing it along the lines of C++ but eventually decided not to.
EDIT - IConvertible is not the reason
There seems to be some confusion about the char.ToBoolean() method.
((IConvertible)someChar).ToBoolean(...);
is a separate issue from Convert.ToBoolean. (Why the explicit conversion first - see here.) The former had to be implemented when char was made IConvertible. The latter could have simply not been created, so the question of why does that method (Convert.ToBoolean) exists seems to be answered only for backwards compatibility + the original intention.
(If I'm the one misunderstanding this - please let me know, of course.)
This should work:
Convert.ToBoolean(Convert.ToInt32(charVar.ToString()))
I have a huge code base and I recently made a change where I changed the type of a parameter from String to a custom class. On the next compile I got all the areas where the impact was, but areas where the input type was of type Object failed. for e.g.
String str = "32"
int i = Convert.ToInt32(str)
Now I have changed String to a new custom type lets say MyCustomClass I would now want following code to fail on next compile
MyCustomClass str = new MyCustomClass("32")
int i = Convert.ToInt32(str)
but it won't as Convert.ToInt32 also accepts type Object. Is there some way I can make a change in MyCustomClass that it's not considered Object anymore.
Please note: Convert.ToInt32 is only used for sample I have many more such functions, so please focus your suggestion/answer to question asked.
Override ToString() and IConvertible
You said in the comments that your intentions are to find places where your object, which had previously been treated as a string, and are now being treated as an object.
In these situations typically, the third-party code would call .ToString() on your object to get something which it can use.
So, Convert.ToInt32(str) is equivalent to Convert.ToInt32(str.ToString()).
If you implement ToString() and IConvertible to return whatever your old version of str looked like then it should continue to work in the same way as the old version.
Probably.
Sorry I know that is not the 100% perfect compile time answer you were looking for, but I think you also know very well that your MyCustomClass will always be considered object.
Possible compile time answer:
Write a tool which uses reflection to iterate over every class/struct/interface in every system/third-party DLL.
Output a load of CS files which contain all these same classes, but just throw NotImplementedException.
(T4 could help you do this)
Compile these classes into dummy.dll
Your .csproj now references only this one dummy.dll, instead of the real dlls.
Your project should compile fine against the dummy dll.
Look at your dummy.cs files and delete any use of object.
Re-compile... and suddenly you get a load of compile time errors showing you anywhere you are using an object.
Impliment an implicit cast from MyCustomClass to String.
public static implicit operator string(MyCustomClass str)
{
return "Legacy respresentation of str";
}
This allows the complier the choice of choosing ToInt32(Object) or ToInt32(String), and I bet it favours the later.
This way all your existing function calls will remain the same so you wont have to be concerned about third party implentation details.
(Sorry, I am not at a computer right now so I can`t test that my assumtion is correct. If you do test this, be sure to consider extension methods, as they can affect the conpilers desision making in unexpected ways)
I'm fairly new to C# but i'm looking to convert an object to an array of unsigned shorts. The original data is an array of WORD's (numerical value WORD) passed as an object. I've attempted the following but keep getting an error.
object temp = Agent.Port("PumpPressure1_01").Value;
ushort[] PP1_01 = ((IEnumerable)temp).Cast<object>()
.Select(x => x == null ? x.ToUshort())
.ToArray();
When I run this I get the following error:
'System.Collections.Generic.IEnumerable<T>' requires '1' type arguments.
The namespaces I used when I get the above error are:
using System.Linq;
using System.Text; // Don't think this is required but added it in case
If I add the following namespaces:
using System.Collections;
using System.Collections.Generic;
I get the following error.
'System.Linq.ParalleIEnumerable.Select<TTSource,TResult>()' is not supported by the language
I'm sure this is an obvious issue but I've been hunting the net for a while and can't find a solution. My best guess is that the Select function isn't correct as this was originally designed to convert an object to an array of strings.
Any help would be great.
Thanks
IEnumerable is a generic interface, so you have to declare the datatype you are using...
To be honest though, I would want to check what that call to
object temp = Agent.Port("PumpPressure1_01").Value;
is actually returning - by inspecting it in the debugger... If it is simply returning a reference to an array of a numeric type, you should be able to simply cast it. What you are doing though is trying to cast each individual item within the array - I suspect that's not what you should be doing - which would be casting the array itself.
Can you give us any API documentation for the Port method on the Agent object so I can see what it is meant to return? Can you try the inspection and see what that gives you?
Why you casting to IEnumerable and then casting it back to object if your temp variable is already of type object?
Also IEnumerable<T> is a generic interface and must specify exact type (as exception also says to you). If you have an array of integers and you want to work with them it should be IEnumerable<int>
Thanks for all the help and feedback.
Unfortunately I was't paying enough attention to the warnings that was posted which seems to be causing the issue.
Warning: Reference to type 'System.Func '2' claims it is defined in 'c:\Windows\Microsoft.NET\Framework64\v2.0.50727mscorlib.dll'. but it could not be found
It seems that there is some issue with the .NET reference. I have another VM which I tested the following solution on and it seemed to work without issue. Looks like I'll have to reinstall the software package to get it to work on the VM i want to use.
The software package I'm using is a custom package that uses C# to build solutions with prebuilt classes made to look like plug and play blocks. You can connect the blocks together drawings lines from one input/output of a block to another. You can then build C# code inside the blocks. Basically c# for dummy's like me..
Example of the blocks:
As for the code, I did have to make some changes as follows but now works a treat. Agent.Port("PumpPressure1_01").Value.RawValue is used to reference the particular ports on the block.
object temp = (object)Agent.Port("PumpPressure1_01").Value.RawValue;
UInt16[] PP1_01 = ((System.Collections.IEnumerable)temp).Cast<object>()
.Select(x => Convert.ToUInt16(x))
.ToArray();
foreach(UInt16 x in PP1_01)
{
Agent.LogDebug("values: " + x.ToString());
}
Again, thanks for all the help. Just need to resolve the issue with the library reference now.
I want to convert NSMutableArray to CLLocationcoordinates2D[]
I tried the following but it gave me an error ,(this kind of type case is not allowed)
NSMutableArray* arrtest ;
// I had added some CLLocationcoordinates2D objects to this
CLLocationcoordinates2D[] locations = (CLLocationcoordinates2D[])arrtest
How could I convert?
If you really have an NSArray which you need to cast in a C# array, do the following:
var locations = NSArray.FromArray<CLLocationCoordinate2D>(arrtest);
However, considering that all Apple APIs in Xamarin.iOS return a C# array instead of an NSArray, you rarely need this. If you created the NSMutableArray yourself, I'd suggest to use a List< CLLocationCoordinate2D> instead.
I was hoping to get some clarity on the use of () before the call of a method (applies to class,struc, etc as well). Firstly I don't know what the action is called so having trouble in pinpointing where to start reading on it, and secondly if you have some explanation on why one would use this that would be great.
In the example below I am interested in the (TestClassRemoting) that is called in front of the Activator.Getobject(...) method.
Example
TestClassRemoting test = (TestClassRemoting)Activator.GetObject(someType,someString);
Now in the scripts, TestClassRemoting is just a class defined with a Text method that will print a string.
in languages like c# and java explicit type conversions are done by specifying the type the data should be converted to inside () brackets. so in your case the object returned by the Activator.GetObject is converted to type TestClassRemoting.
find more info here,
http://en.wikipedia.org/wiki/Type_conversion