Click here to Skip to main content
15,892,674 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
When trying to compile the following two code lines the compiler is complaining with error "CS1503 Argument1: cannot convert from 'char' to 'string'".
string test = "abcd";
bool result = test.StartsWith('a');

When I pass the letter 'a' as a string the method works as expected.
The MS documentation tells me that there exists an overload which takes a char as a single argument.
String.StartsWith Method (System) | Microsoft Docs[^]

Why does the compiler not find this method?

What I have tried:

I also tried:
string test = "abcd";
char ch = 'a';
bool result = test.StartsWith(ch);

which produced the same compiler error.
Posted
Updated 9-Aug-22 8:05am
v2
Comments
[no name] 9-Aug-22 15:01pm    
Use "Go to definition" in VS (code) to confirm was is supported for that method in the version your are targeting.
Member 13566383 9-Aug-22 15:52pm    
That's a helpful hint. I hope I will remember it in similar situations in the future.

1 solution

Because it was introduced with .NET 6, and you aren't using that version?

Writing an extension method for it would be trivial though, as a string can be trated as an array of characters:
bool result = test[0] == 'a';
 
Share this answer
 
Comments
Member 13566383 9-Aug-22 15:39pm    
That's the solution I implemented as calling the function didn't work.
My NetFrameWork version is 4.6.1 so your suspicion is correct.
I not even thought about the possibility that such trivial function is a feature available in newer versions only.
PIEBALDconsult 9-Aug-22 17:37pm    
And a pretty pointless one at that. Just test the first character.
OriginalGriff 10-Aug-22 0:41am    
Yes, but I can see why they added it later - it makes code look more consistent.
That's why I suggested an Extension Method - it's easy to add and can be #if excluded in .NET 6 and above.
Richard Deeming 11-Aug-22 4:31am    
It was introduced with .NET Core 2.0 according to the documentation. :)
OriginalGriff 11-Aug-22 5:03am    
Core 2.0, Framework 6.0.
It's definitely not in "vanilla" .NET 4.8 (which is what I'm using by default)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900