I want to obtain the Unicode code of a certain char. The declared function does not accept the argument.
the code blocks at line string str01 = GetEscapeSequence(char c1);
The error:
Error CS1525: Unexpected symbol c1', expecting.' (CS1525)
The code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace problem_005
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Insert the caracter");
char c1 = char.Parse(Console.ReadLine());
string str01 = GetEscapeSequence(char c1);
Console.WriteLine("the Unicode is ={0}", str01);
Console.WriteLine("m");
}
public string GetEscapeSequence(char c)
{
return "\\u" + ((int)c).ToString("X4");
}
}
}
To call a method in C#, you don't need to specify the parameter type. Just
string str01 = GetEscapeSequence(c1);
will suffice.
Also, as main is a static method, you must make GetEscapeSequence static as well:
public static string GetEscapeSequence(char c)
Related
I have been working on some TDD Kata and have it nearly finished but was running into the CS1519 error. VS is telling me where the error is occurring but not sure how to go about fixing the solution. This is my first crack at doing TDD of any kind and looking for some general pointers as well.
I've been on stack overflow looking at other threads about talking about CS1519 but none of them (that I could find) seem to answer my exact question. Also, have checked out Stack Exchange for specific TDD Kata questions but needing more explanation.
using System;
using System.Linq;
namespace ChallengeCode
{
public class Calculator
{
public int Main(string number)
{
TestUnits();
if (string.IsNullOrEmpty(number))
return 0;
var numberArray = number.Replace('\n', ',').Split(',');
numberArray = NewMethod(numberArray);
NonNegValidate(numberArray);
var numberArrayInt = numberArray.Select(x => int.Parse(x)).ToArray();
return numberArrayInt.Where(x => x <= 1000).Sum(x => x);
}
private static void TestUnits()
{
throw new NotImplementedException();
}
internal static double Add(string number)
{
throw new NotImplementedException();
}
private static string[] NewMethod(string[] numberArray)
{
if (numberArray[0].StartsWith("//"))
{
var delimiter = Convert.ToChar(numberArray[0].Remove(0, 2).Distinct());
foreach (var delimiters in numberArray)
{
numberArray[1] = numberArray[1].Replace(delimiter, ',');
}
numberArray = numberArray[1].Split(',');
}
return numberArray;
}
private static void NonNegValidate(string[] numberArray)
{
if (numberArray.Any(x => int.Parse(x) < 0))
throw new Exception($"negatives not allowed {string.Join(" ", numberArray.Where(x => int.Parse(x) < 0))}");
}
}
}
Here is the code that I am using for Program.cs
using NUnit.Framework;
using System;
namespace ChallengeCode
{
class TestUnits
{
public void Add_Number_ReturnsSum(int expected, string number)
{
Assert.AreEqual(expected, Calculator.Add(number));
}
public void Add_NegNumber_Throw_An_Exception()
{
const string number = "1\n-2,-3";
var exception = Assert.Throws<Exception>(() => Calculator.Add(number));
Assert.AreEqual("negatives not allowed -2 -3", exception.Message);
}
}
}
More Details:
Screenshot of Code
I think your entry point is expecting an array instead of a single string.
I changed your code to this and it compiled. This is using the first element of your array... but has separate exceptions.
static int Main(string[] number)
{
TestUnits();
if (string.IsNullOrEmpty(number[0]))
return 0;
var numberArray = number[0].Replace('\n', ',')
.Split(',');
}
it's throwing more exceptions for being outside the bounds of this array because I'm not aware of what context this program is being used in. I assume you have another program feeding the string parameter into this one?
The Main method can be declared with or without a string[] parameter that contains command-line arguments.
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/main-and-command-args/
public void Test ()
{
string myString = "hello";
}
public void Method (string text)
{
COnsole.WriteLine ( ... + " : " + text ); // should print "myString : hello"
}
Is it possible to get name of variable passed to a method?
I want to achieve this:
Ensure.NotNull (instnce); // should throw: throw new ArgumentNullException ("instance");
Is it possible? WIth caller info or something similiar?
Without nameof operator?
Problem with reflection is that, once the C# code is compiled, it will no longer have the variable names. The only way to do this is to promote the variable to a closure, however, you wouldn't be able to call it from a function like you are doing because it would output the new variable name in your function. This would work:
using System;
using System.Linq.Expressions;
public class Program
{
public static void Main()
{
string myString = "My Hello string variable";
// Prints "myString : My Hello String Variable
Console.WriteLine("{0} : {1}", GetVariableName(() => myString), myString);
}
public static string GetVariableName<T>(Expression<Func<T>> expr)
{
var body = (MemberExpression)expr.Body;
return body.Member.Name;
}
}
This would NOT work though:
using System;
using System.Linq.Expressions;
public class Program
{
public static void Main()
{
string myString = "test";
// This will print "myVar : test"
Method(myString);
}
public static void Method(string myVar)
{
Console.WriteLine("{0} : {1}", GetVariableName(() => myVar), myVar);
}
public static string GetVariableName<T>(Expression<Func<T>> expr)
{
var body = (MemberExpression)expr.Body;
return body.Member.Name;
}
}
This has been driving me mad for a while now. I have a class which contains other classes. I need to loop through the first class looking for typeof second class then retreive the value of the fields.
the below code obviously fails on the line
Console.WriteLine(field.GetValue(mFC.field.secondClassString));
as this isn't a valid field. Possibly I'm going about this the wrong way - any ideas?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
MyFirstClass mFC = new MyFirstClass();
FieldInfo[] fI = mFC.GetType().GetFields();
foreach (FieldInfo field in fI)
{
if (field.FieldType.Name == "MySecondClass")
{
//get the fields
Console.WriteLine(field.GetValue(mFC.field.secondClassString));
}
}
}
}
class MyFirstClass
{
public MySecondClass firstMSC = new MySecondClass("First Instance");
public MySecondClass secondMSC = new MySecondClass("Second Instance");
public string firstClassString = "I'm from the first class";
public int firstClassInt = 5;
}
class MySecondClass
{
public MySecondClass(string input)
{
this.secondClassString = input;
}
public string secondClassString;
public int secondClassInt = 10;
}
}
field.GetValue accepts the instance from which it gets the field value.
In your case I would expect it should be field.GetValue(mFC).
Also field.FieldType.Name == "MySecondClass" is not the best way to check the type as type name change will cause code to break. I recommend replacing it with field.FieldType == typeof(MySecondClass).
((MySecondClass)field.GetValue(mFC)).secondClassString;
use this inside console.writeline
Not sure if this is possible but im wondering how I catch the return of two methods that are assigned to the same delegate (multicast). I basically wondered if there is a way to catch each return value? Perhaps I have to iterate over it, not really sure..
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MutiCastDelegate2
{
class Program
{
delegate string HelloWorldDelegate();
static void Main(string[] args)
{
HelloWorldDelegate myDel1 = ReturnHelloWorld;
HelloWorldDelegate myDel2 = ReturnHelloWorld2;
HelloWorldDelegate myMultiDelegate = myDel1 + myDel2;
Console.WriteLine(myMultiDelegate());
Console.ReadLine();
}
public static string ReturnHelloWorld()
{
return "Return Hello World";
}
public static string ReturnHelloWorld2()
{
return "Return Hello World 2";
}
}
}
You can use MulticastDelegate.GetInvocationList() to get access to each delegate in the list, then you just have to call each one and retrieve the results:
var delegates = myMultiDelegate.GetInvocationList();
foreach (var d in delegates)
{
string result = (string) d.DynamicInvoke();
}
Not sure what I'm doing wrong here. The extension method is not recognized.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using StringExtensions;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
RunTests();
}
static void RunTests()
{
try
{
///SafeFormat
SafeFormat("Hi There");
SafeFormat("test {0}", "value");
SafeFormat("test missing second value {0} - {1}", "test1");
SafeFormat("{0}");
//regular format
RegularFormat("Hi There");
RegularFormat("test {0}", "value");
RegularFormat("test missing second value {0} - {1}", "test1");
RegularFormat("{0}");
///Fails to recognize the extension method here
string.SafeFormat("Hello");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Console.ReadLine();
}
private static void RegularFormat(string fmt, params object[] args)
{
Console.WriteLine(String.Format(fmt, args));
}
private static void SafeFormat(string fmt, params object[] args)
{
string errorString = fmt;
try
{
errorString = String.Format(fmt, args);
}
catch (System.FormatException) { } //logging string arguments were not correct
Console.WriteLine(errorString);
}
}
}
namespace StringExtensions
{
public static class StringExtensionsClass
{
public static string SafeFormat(this string s, string fmt, params object[] args)
{
string formattedString = fmt;
try
{
formattedString = String.Format(fmt, args);
}
catch (System.FormatException) { } //logging string arguments were not correct
return formattedString;
}
}
}
You're trying to call it on the type string. You need to call it on a string instance, e.g.
"{0}".SafeFormat("Hello");
Admittedly that won't do what you want it to, because the SafeFormat method is actually completely ignoring the first parameter (s) anyway. It should look like this:
public static string SafeFormat(this string fmt, params object[] args)
{
string formattedString = fmt;
try
{
formattedString = String.Format(fmt, args);
}
catch (FormatException) {} //logging string arguments were not correct
return formattedString;
}
Then you can call:
"{0} {1}".SafeFormat("Hi", "there");
The point of extension methods is that they look like instance methods on the extended type. You can't create extension methods which appear to be static methods on the extended type.
You're defining an instance extension method, and then trying to use it as a static method. (C# is not capable of defining a static extension method, though F# is for that matter.)
Instead of:
result = string.SafeFormat("Hello");
you want something like:
result = "Hello".SafeFormat();
i.e. You're operating on the string instance ("Hello" in this case).
Extension methods appear on instances of a type, not the type itself (e.g. static members).
try
"Hello".SafeFormat("{0} {1}", "two", "words")