Hi is there any change to write static extension in Swift like is in C#? I mean in C# i can write same thing like this:
public static class MyExtensions
{
public static int WordCount(this String str)
{
return str.Split(new char[] { ' ', '.', '?' },
StringSplitOptions.RemoveEmptyEntries).Length;
}
}
and call it like this:
var s = ""; var x = s.WordCount();
I know i can do same thing in swift, but it work only on class types. On static types I must write something like :
var str:String?
let s = String.IsNilOrEmpty(str)
for this extension:
extension String {
static func isNilOrEmpty(str: String?) -> Bool{
if str == nil {
return true
}
if str!.isEmpty{
return true
}
return false
}
}
Is there change to call it like this:
let s = str.IsNilOrEmpty()
Thanks for help or kicking out to right way.
You can define functions with the same name, one static, one not static.
extension String {
static func myfunc() -> String {
return "static"
}
func myfunc() -> String {
return "func"
}
}
let s3 = ""
print(s3.myfunc()) // output = "func"
print(String.myfunc()) // output = "static"
In this case, if 'someOptionalString' is nil, then it will not call the function.
let some = someOptionalString.IsNilOrEmpty()
Related
I would like to convert (but i think it's not possible) a string into a bool, in this way:
string a = "b.Contains('!')";
private void print(string condition)
{
string b = "Have a nice day!";
/* Some kind of conversion here for condition parameter */
/* like bool.Parse(condition) or Bool.Convert(condition) */
if(condition)
{
Console.Write("String contains !-character.");
}
}
Mind that the bool-string has to be passed to the function as a parameter.
Is there a way to achieve this?
There is no built in way to parse your string to a expression.
But of your goal is to sent the expression to an other function you could do this
using System;
public class Program
{
public static void Main()
{
print(x=>x.Contains("!"));
}
private static void print(Func<string,bool> condition)
{
string b = "Have a nice day!";
/* Some kind of conversion here for condition parameter */
/* like bool.Parse(condition) or Bool.Convert(condition) */
if(condition.Invoke(b))
{
Console.Write("String contains !-character.");
}
}
}
if you would like a non build in way you could look at : Is there a tool for parsing a string to create a C# func?
I think you need to use an auxiliar bool variable, like this example..
bool aux = false;
private bool print(string condition)
{
string b = "Have a nice day!";
if(b.Contains(condition))
aux = true;
return aux;
}
Or the same example without auxiliar.
private bool print(string condition)
{
string b = "Have a nice day!";
return b.Contains(condition);
}
Then call the method print to check if it is true or false and write the message you want
if(print("!"))
Console.WriteLine("String contains !-character.");
Is it possible to give a C# Object like
public string Name
{
get { return _name; }
set { _name = value; }
}
a Method doing something like:
private void addTextToName(){
_name = _name + " - Test";
}
so that I can call it like
Name.addTextToName();
Because (where I come from) in JavaScript you can do such things with .prototype
Is there any way to do this in C#?
If you are asking can I add a method to a string? then yes. Look at extension methods.
public static string AddTextToName(this string s)
{
return s + " - Test";
}
Use it like this:
"Hello".AddTextToName();
Will return Hello - test.
Yes, there is a way for C# Objects (you used a string there, but though...).
Take a look at the so-called "extension methods" in C# as they are exactly what you need I think.
For further reference, look e.g. here: https://msdn.microsoft.com/en-us/library/vstudio/bb383977%28v=vs.110%29.aspx (the magic is in the this as parameter for the method)
Using the extension method.
class Program
{
static void Main()
{
Example e = new Example();
e.Name = "Hello World";
var x = e.Name;
var y = x.addTextToName();
Console.WriteLine(y);
Console.ReadLine();
}
}
class Example
{
public string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
}
public static class MyExtensions
{
public static string addTextToName(this string str)
{
return str += " - Test";
}
}
have a php code like this,going to convert it in to C#.
function isValid($n){
if (preg_match("/\d+/",$n) > 0 && $n<1000) {
return true;
}
return false;
}
Here is my try,BUT error shown Error is "expected class, delegate, enum, interface or struct error C#"
public string IsValidate(string Item)
{
string Result = Item;
try
{
Result = System.Text.RegularExpressions.Regex.Replace(InputTxt, #"(\\)([\000\010\011\012\015\032\042\047\134\140])", "$2");
}
catch(Exception ex)
{
console.WriteLine(ex.Message)
}
return Result;
}
What is the error,Is there any other way to implement this better than my try ?
i got this snippet from here code
You haven't define this method inside a class/struct that is why you are getting this error. You may define this method inside a class.
public class MyValidator
{
public string IsValidate(string Item)
{
//Your code here
}
}
Later you can use it like:
MyValidator validator = new MyValidator();
validator.IsValid("Your string");
Also you are missing semicolon at the end of the Console.Write statement, plus 'c' for Console should be in uppercase
Edit:
Since in your php code, it looks like you are trying to see if the string passed is an integer and it is less than 1000, you may use the int.TryParse like the following:
public class MyValidator
{
public bool IsValidate(string Item)
{
string Result = Item;
int val;
if (int.TryParse(Item, out val) && val > 0 && val < 1000)
{
return true;
}
else
{
return false;
}
}
}
In you main method you can do:
static void Main()
{
MyValidator validator = new MyValidator();
Console.WriteLine(validator.IsValidate("asdf123")); // This will print false
Console.WriteLine(validator.IsValidate("999")); //This will print true
Console.WriteLine(validator.IsValidate("1001")); //This will print false
}
In C# a method must be placed inside a class or struct:
public class Validator {
public string IsValidate(string item) {
...
}
}
In this case I would probably translate it like this:
public static class Validator {
public static bool IsValid(string item) {
int value;
return int.TryParse(item, out value)
&& value > 0 && value < 1000;
}
}
You could define your function inside a static class such that you dont have to create an instance of it before invoking the function. Like,
public static class Validator
{
public static string IsValidate(string item)
{
// ...
}
}
Then, you can call it using:
Validator.IsValidate("String to validate")
EDIT: You could then check that your function is returning what you expect by doing:
if(Validator.IsValidate("String to validate") == "Expected result")
{
/* Logic to be executed here */
}
I've trying to achieve something like this:
class App {
static void Main(string[] args) {
System.Console.WriteLine(new Test("abc")); //output: 'abc'
System.Console.ReadLine();
}
}
I can do this passing by an variable:
class Test {
public static string str;
public Test (string input) { str = input; }
public override string ToString() {
return str;
}
}
works fine.
But, my desire is do something as:
class Test {
public static string input;
public Test (out input) { }
public override string ToString() {
return input;
}
}
System.Console.WriteLine(new Test("abc test")); //abc test
Don't works.
How I do this?
Thanks,advanced.
You can't. The variable approach is exactly the correct way, although the variable shouldn't be declared static, and shouldn't be a public field.
class Test {
public string Input {get;set;}
public Test (string input) { Input = input; }
public override string ToString() {
return Input;
}
}
I have an impression that you're not entirely understand what out keyword means. Essentially when you're writing something like void MyMethod(out string var) it means you want to return some value from method, not pass it into method.
For example there's bool Int32.TryParse(string s, out int result). It parses string s, returns if parse was successful and places parsed number to result. Thus, to correctly use out you should have real variable at the calling place. So you can't write Int32.Parse("10", 0) because this method can't assign result of 10 to 0. It needs real variable, like that:
int result;
bool success = Int32.TryParse("10", out result);
So, your desire is somewhat else - it is not in line with language designer's intentions for out :)
You can do anonymous functions in C# like you can in JavaScript:
JavaScript:
var s = (function ()
{
return "Hello World!";
}());
C#:
var s = new Func<String>(() =>
{
return "Hello World!";
})();
... In JavaScript you can pass functions to be executed by other functions. On top of that; you can pass parameters to the function which gets executed:
var f = function (message) // function to be executed
{
alert(message);
};
function execute(f) // function executing another function
{
f("Hello World!"); // executing f; passing parameter ("message")
}
Is the above example possible in C#?
Update
Use-case: I am iterating over a bunch of database, logging specific entities. Instead of calling my second function (F()) inside Log() of Logger, I'd like to call F() outside the class.
... Something along the lines of:
public void F(String databaseName)
{
}
public class Logger
{
public void Log(Function f)
{
var databaseName = "";
f(databaseName);
}
}
Absolutely - you just need to give the method an appropriate signature:
public void Execute(Action<string> action)
{
action("Hello world");
}
...
Execute(x => Console.WriteLine(x));
Note that you do have to specify the particular delegate type in the parameter - you can't just declare it as Delegate for example.
EDIT: Your database example is exactly the same as this - you want to pass in a string and not get any output, which is exactly what Action<string> does. Except if you're trying to call an existing method (F() in your code) you don't even need a lambda expression - you can use method group conversions instead:
public void F(String databaseName)
{
}
public class Logger
{
public void Log(Action<string> f)
{
var databaseName = "";
f(databaseName);
}
}
// Call it like this:
Logger logger = new Logger(...);
logger.Log(F);
You can pass delegate:
var f = (Action<string>)
(x =>
{
Console.WriteLine(x);
}
);
var execute = (Action<Action<string>>)
(cmd =>
{
cmd("Hello");
}
);
execute(f);
according your Update part:
you need a container to keep your functions
IList<Action<string>> actionList = new List<Action<Sstring>>();
in your Log() function you can add your F() to the container:
actionList.Add(F);
then invoke the function(s) somewhere outside:
foreach (Action<string> func in actionList)
{
func("databasename");
}
Like:
var s = new Func<String, string>((string name) =>
{
return string.Format("Hello {0}!", name);
});
?