public bool PosTest2()
    {
        bool retVal = true;

        const string c_TEST_DESC = "PosTes2: Verify the Nullable object's HasValue is false";
        const string c_TEST_ID = "P002";

        int? nullObj = new Nullable<int>();

        TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);

        try
        {
            if (nullObj.GetValueOrDefault() != 0)
            {
                string errorDesc = "value is not 0 as expected: Actual(" + nullObj.GetValueOrDefault() + ")";
                TestLibrary.TestFramework.LogError("003 " + "TestID_" + c_TEST_ID, errorDesc);
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("004 " + "TestID_" + c_TEST_ID, "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
    public bool PosTest1()
    {
        bool retVal = true;

        const string c_TEST_DESC = "PosTest1: Verify the Nullable object's HasValue is true";
        const string c_TEST_ID = "P001";

        int value = TestLibrary.Generator.GetInt32(-55);
        int? nullObj = new Nullable<int>(value);

        TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);

        try
        {
            if (nullObj.GetValueOrDefault() != value)
            {
                string errorDesc = "value is not " + value + " as expected: Actual(" + nullObj.GetValueOrDefault() + ")";
                TestLibrary.TestFramework.LogError("001 " + "TestID_" + c_TEST_ID, errorDesc);
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("002 " + "TestID_" + c_TEST_ID, "Unexpected exception: " + e + "\n value is " + value);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
Exemple #3
0
        static void Display(Nullable<int> x) 
        {
            Console.WriteLine("HasValue: {0}", x.HasValue);
            if (x.HasValue)
            {
                Console.WriteLine("Value: {0}", x.Value);
                Console.WriteLine("Explicti conversion: {0}", (int)x);
            }

            Console.WriteLine("GetValueOrdDefault(): {0}", x.GetValueOrDefault());
            Console.WriteLine("GetValueOrDefaullt(10): {0}", x.GetValueOrDefault(10));

            Console.WriteLine("ToString(): \"{0}\"", x.ToString());
            Console.WriteLine("GetHashCode(): {0}", x.GetHashCode());
        }
Exemple #4
0
        public GiveNPCTask(int npcType, int[] giveItem, int[] stack, string text, string objective = null, bool requireAll = true, bool takeItems = true, Nullable <int> optionalReward = null)
        {
            _npcType    = npcType;
            _objective  = objective;
            _itemIDs    = giveItem;
            _itemStacks = stack;

            if (giveItem.Length <= 0 || stack.Length <= 0)             //Error about empty arrays
            {
                SpiritMod.Instance.Logger.Error($"A Give NPC Task with an empty _itemIDs or _itemStacks list has been added.\nLengths: _itemID: {giveItem.Length}\t_itemStacks: {stack.Length}.",
                                                new Exception("GiveNPCTask with either no itemIDs or stack sizes has been added. Report to mod devs."));
            }
            if (giveItem.Length != stack.Length)
            {
                SpiritMod.Instance.Logger.Error($"A Give NPC Task with mismatched _itemIDs and _itemStacks sizes has been added.",
                                                new Exception("Mismatched GiveNPCTask quest item list/stack added. Report to mod devs."));
            }

            RequireAllItems = requireAll;
            TakeItems       = takeItems;
            _optionalReward = optionalReward.GetValueOrDefault();
            NPCText         = text;

            _takenItems = false;
        }
Exemple #5
0
        public static void Main(string[] args)
        {
            var number = new Nullable <int>(5);

            Console.WriteLine("Has value? " + number.HasValue);
            Console.WriteLine("Value : " + number.GetValueOrDefault());
        }
Exemple #6
0
        static void Main(string[] args)
        {
            Nullable <int> i = null;

            Console.WriteLine("i=" + i);
            Console.WriteLine(i.GetValueOrDefault());
            if (i.HasValue)
            {
                Console.WriteLine(i.Value); // or Console.WriteLine(i)
            }
            else
            {
                Console.WriteLine("Null");
            }
            int?x = null;
            int j = x ?? 0;

            Console.WriteLine("x = {0}, j = {1}", x, j);
            Console.WriteLine("x >= 10 ? {0}", x >= 10);
            Console.WriteLine("x < 10 ? {0}", x < 10);
            if (Nullable.Compare <int>(i, j) < 0)
            {
                Console.WriteLine("i < j");
            }
            else if (Nullable.Compare <int>(i, j) > 0)
            {
                Console.WriteLine("i > j");
            }
            else
            {
                Console.WriteLine("i = j");
            }
        }
        /// <summary>
        ///     Writes HTTP message to wrapped stream
        /// </summary>
        /// <param name="header">HTTP message header</param>
        /// <param name="body">HTTP message body</param>
        /// <param name="bodyLength">expected length of HTTP message body</param>
        public void Write(HttpMessageHeader header, Stream body = null, Nullable <long> bodyLength = null)
        {
            ContractUtils.Requires <ArgumentNullException>(header != null, "header");

            var writer = new StreamWriter(OutputStream, Encoding.ASCII);

            writer.WriteLine(header.StartLine);

            foreach (string headerLine in header.Headers.Lines)
            {
                writer.WriteLine(headerLine);
            }

            writer.WriteLine();
            writer.Flush();

            if (body == null)
            {
                return;
            }

            if (WriteBody(header, body, bodyLength.GetValueOrDefault(0)))
            {
                writer.WriteLine();
                writer.Flush();
            }
        }
    public bool PosTest1()
    {
        bool retVal = true;

        const string c_TEST_DESC = "PosTest1: Verify the Nullable object's HasValue is true";
        const string c_TEST_ID   = "P001";

        int value   = TestLibrary.Generator.GetInt32(-55);
        int?nullObj = new Nullable <int>(value);

        TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);

        try
        {
            if (nullObj.GetValueOrDefault() != value)
            {
                string errorDesc = "value is not " + value + " as expected: Actual(" + nullObj.GetValueOrDefault() + ")";
                TestLibrary.TestFramework.LogError("001 " + "TestID_" + c_TEST_ID, errorDesc);
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("002 " + "TestID_" + c_TEST_ID, "Unexpected exception: " + e + "\n value is " + value);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return(retVal);
    }
Exemple #9
0
        public static Nullable <T> ConvertFromType <T>(string value, CultureInfo culture)
            where T : struct
        {
            Nullable <T> returnValue = new Nullable <T>();

            returnValue = returnValue.GetValueOrDefault();

            if (value == null)
            {
                return(returnValue);
            }

            EnumConverter converter = GetEnumConverter <T>();

            if (converter == null)
            {
                return(returnValue);
            }

            if (converter.CanConvertFrom(value.GetType()))
            {
                object converted = converter.ConvertFrom(null, culture, value);

                if (converted != null && (converted is T))
                {
                    returnValue = (T)converted;
                }
            }

            return(returnValue);
        }
Exemple #10
0
 static void Display(Nullable <int> x)
 {
     Console.WriteLine("HasValue: {0}", x.HasValue);
     if (x.HasValue)
     {
         Console.WriteLine("Value: {0}", x.Value);
         Console.WriteLine("Explicit conversion: {0}", (int)x);
     }
     Console.WriteLine("GetValueOrDefault(): {0}",
                       x.GetValueOrDefault());
     Console.WriteLine("GetValueOrDefault(10): {0}",
                       x.GetValueOrDefault(10));
     Console.WriteLine("ToString(): \"{0}\"", x.ToString());
     Console.WriteLine("GetHashCode(): {0}", x.GetHashCode());
     Console.WriteLine();
 }
Exemple #11
0
        static void Main(string[] args)
        {
            Console.WriteLine("Enter a number  :");
            string num = Console.ReadLine();
            int num1 = int.Parse(num);
            var number = new Nullable<int>(num1);

            Console.WriteLine("Has a value ?:  "+ number.HasValue);
            Console.WriteLine("Value :  "+ number.GetValueOrDefault());
            Console.WriteLine("");

            Console.WriteLine("enter a number :");
            string index = Console.ReadLine();
            Console.WriteLine("enter a Name :");
            string name = Console.ReadLine();

            var Nlist = new GenericDictionary<string,string>();
            Nlist.Add(index, name);

            var NList2 = new GenList<string,string>();
            NList2.Add(index,name);

            List<string> NewList = new List<string> { index, name, num };
            Console.WriteLine(NewList.LongCount());

            Console.WriteLine("choose 1, 2 or 3");
            int n = int.Parse(Console.ReadLine());
            Console.WriteLine(NewList[n-1]);


        }
        static void Main(string[] args)
        {
            //var numbers = new GenericList<int>();
            //numbers.Add(10);

            //var books = new GenericList<Book>();
            //books.Add(new Book() { Isbn = "321321", Title = "Test" });

            ////System.Collections.Generic

            //var dictionary = new GenericDictionary<string, Book>();
            //dictionary.Add("1234", new Book());

            var number = new Nullable<int>(5);
            Console.WriteLine("Has Value ? " + number.HasValue);
            Console.WriteLine("Value : " + number.GetValueOrDefault());

            var number2 = new Nullable<int>();
            Console.WriteLine("Has Value ? " + number2.HasValue);
            Console.WriteLine("Value : " + number2.GetValueOrDefault());

            Console.ReadLine();

            var dc = new DiscountCaculator<Book>();
            dc.CalculateDiscount(new Book());
        }
Exemple #13
0
        static void Main(string[] args)
        {
            Nullable <int> i = null;

            Console.WriteLine("The value is {0}", i.GetValueOrDefault());

            int    age  = 15;
            string vote = "";

            vote = age > 18 ? "Can cast vote" : "Can not cast vote";

            Console.WriteLine(vote);

            //Nullable<int> a;
            int?   a;
            Object db = null;

            a = db == null ? 0 : (int)db;
            int j = a ?? 0;

            string k = "";
            string f = null;

            k = f ?? "empty";
            Console.WriteLine("Value of K: " + k);



            dynamic ab = "this is string";
            var     aa = 10;
        }
Exemple #14
0
 public static void Main(string[] args)
 {
     //			var book = new Book{Isbn = }
     var number = new Nullable<int>(5);
     //			Console.WriteLine (number.HasValue);
     Console.WriteLine (number.GetValueOrDefault());
 }
Exemple #15
0
        static void Main(string[] args)
        {
            Nullable <DateTime> date0 = DateTime.Today; // Nullable is a generic structure in the system space
            Nullable <DateTime> date9 = null;           // Nullable is a generic structure in the system space
            DateTime?           date1 = null;


            Console.WriteLine("GetValueOrDefault(): " + date1.GetValueOrDefault());
            Console.WriteLine("HasValue: " + date1.HasValue);
            //Console.WriteLine("date.value: " + date0.Value);


            DateTime?date2 = new DateTime(2020, 1, 1);
            DateTime date3 = date1.GetValueOrDefault(); // date3 can either get default value or the actual value if it is available
            DateTime date4 = date3;

            Console.WriteLine("date3: " + date3);


            if (date0 != null)
            {
                date1 = date0.GetValueOrDefault();
                Console.WriteLine("when date0 is not null: " + date1);
            }
            else
            {
                date1 = DateTime.Today;
                Console.WriteLine(date1);
            }

            DateTime?date5 = DateTime.Today.AddDays(2);
            DateTime date6 = date5 ?? DateTime.Today;

            Console.WriteLine("Date6: " + date6);
        }
Exemple #16
0
        static void Main(string[] args)
        {
            Nullable <int> i = null;

            Console.WriteLine(i.GetValueOrDefault());
            Console.WriteLine(i);
            if (i.HasValue)
            {
                Console.WriteLine("Has Value: " + i.Value);
            }
            else
            {
                Console.WriteLine("Null");
            }

            int    age  = 18;
            string vote = "";

            if (age >= 18)
            {
                vote = "Can cast vote";
            }
            else
            {
                vote = "Can not cast vote";
            }
            Console.WriteLine(vote);

            vote = age >= 18 ? "Can cast vote" : "Can not cast vote";

            var     ii = "10.0"; //fix the datatype in compile time
            dynamic ic = 10.0;   //fix the datatype in run time

            Console.WriteLine(ii);
        }
Exemple #17
0
        public static void Executar()
        {
            Nullable <int> num1 = null;
            int?           num2 = null;

            if (num1.HasValue)
            {
                Console.WriteLine("Valor de num: {0}", num1);
            }
            else
            {
                Console.WriteLine("A variável não possui valor.");
            }

            int valor = num1 ?? 1000;

            Console.WriteLine(valor);

            bool?booleana  = null;
            bool resultado = booleana.GetValueOrDefault();

            Console.WriteLine(resultado);

            try
            {
                int x = num1.GetValueOrDefault();
                int y = num2.GetValueOrDefault();
                Console.WriteLine(x + y);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Exemple #18
0
    static void Main()
    {
        Console.Title = "12. Null Values Arithmetic";
        int    intNum    = 3;
        double doubleNum = 4.23434;

        Console.WriteLine("intNum = {0}", intNum);
        Console.WriteLine("doubleNum = {0}", doubleNum);
        int?intNull = null;             //Console.WriteLine(intNull.HasValue); --> False
        Nullable <double> doubleNull = null;

        Console.WriteLine("intNull:     {0}", intNull);
        Console.WriteLine("doubleNull:  {0}", doubleNull);
        intNull    = intNull + 10;
        doubleNull = doubleNull * 12;
        Console.WriteLine("intNull + 10:    {0}", intNull);
        Console.WriteLine("doubleNull * 12: {0}", doubleNull);
        intNum    = intNull.GetValueOrDefault();
        doubleNum = doubleNull.GetValueOrDefault();
        Console.WriteLine("\nafter null value has been assigned to an integer type variable, intNum = {0}", intNum);
        Console.WriteLine("after null value has been assigned to a double type variable, doubleNum = {0}\n", doubleNum);
        intNum     = intNum + 5;
        doubleNum += 1.34535356;        // doubleNum = doubleNum + 1.34535356
        Console.WriteLine("intNum + 5 = {0}", intNum);
        Console.WriteLine("doubleNum + 1.34535356 = {0}\n", doubleNum);
        //intNum = intNum + null;
        //Console.WriteLine(intNum); --> cause an error
    }
Exemple #19
0
        public static void Main()
        {
            LinkedList <string> ienumerableLinkedList =
                new LinkedList <string> ("First element",
                                         new LinkedList <string> ("Second element",
                                                                  new LinkedList <string> ("Third element")));

            foreach (var element in ienumerableLinkedList)
            {
                Nullable <decimal> number = null;
                Console.WriteLine("LinkedList -> {0},\nNullable -> {1}",
                                  element, number.GetValueOrDefault());
            }

            Console.WriteLine();
            ValueType valType = 10;

            Console.WriteLine("ValueType valType = {0}, {0} is {1}", valType, valType.GetType());
            valType = 6.3;
            Console.WriteLine("valType = {0}, {0} is {1}", valType, valType.GetType());
            valType = 10000000000000000000;
            Console.WriteLine("valType = {0}, {0} is {1}", valType, valType.GetType());
            decimal numDec = 100;

            valType = numDec; // boxing (stak -> heap)
            Console.WriteLine("decimal numDec = {0}, valType = numDec, valType is {1}", numDec, valType.GetType());
            //int numInt = (int)valType; // return InvalidCastException
            int numInt = (int)(decimal)valType; // unboxing (heap -> stak)

            Console.WriteLine("int numInt = (int)(decimal)valType, numInt = {0}", numInt);
        }
Exemple #20
0
        static void Main(string[] args)
        {
            // Does not compile because it is a value type and value types can not be null
            // DateTime date = null;

            // Nullable makes value types nullable
            Nullable <DateTime> date1 = null;

            // Gets the value or the default value for the data type
            Console.WriteLine(date1.GetValueOrDefault());

            // A shorter version
            DateTime?date2 = null;

            // Gets the value or the default value for the data type
            Console.WriteLine(date2.GetValueOrDefault());

            // Null Coalescing Operator
            DateTime today;

            // This means if not null take date2 else DateTime.Now
            today = date2 ?? DateTime.Now;
            Console.WriteLine(today);

            // The Null Coalescing Operator is the same like this but shorter
            if (date2 != null)
            {
                today = date2.GetValueOrDefault();
            }
            else
            {
                today = DateTime.Now;
            }
        }
        public void NullableTest2()
        {
            Nullable <int> number = new Nullable <int>();

            Assert.False(number.HasValue);
            Assert.Equal(expected: 0, actual: number.GetValueOrDefault());
        }
Exemple #22
0
        public void Method()
        {
            int             i = 10;
            bool            b = true;
            bool?           flag;
            int?            num;
            Nullable <int>  num2;
            Nullable <int>  num3 = new Nullable <int>(100);
            Nullable <bool> xyz  = false;
            char?           ch;

            bool hasValue = xyz.HasValue || num3.HasValue;
            int  num3_    = num3.Value;
            bool f        = flag.HasValue ? flag.Value : true;

            xyz  = true;
            num2 = 10;
            num  = 1;

            bool boolVal = flag.GetValueOrDefault();
            char textVal = ch.GetValueOrDefault();
            int  numVal  = num3.GetValueOrDefault();
            Type t       = typeof(Nullable <int>);
            Type t2      = typeof(Nullable <string>);
        }
        public void NullableTest1()
        {
            Nullable <int> number = new Nullable <int>(5);

            Assert.True(number.HasValue);
            Assert.Equal(expected: 5, actual: number.GetValueOrDefault());
        }
Exemple #24
0
        public static async Task LogProjectionStarted(
            Guid queryGuid,
            string queryName,
            string projectionTypeName,
            string domainName,
            string aggregateTypeName,
            string aggregateInstanceKey,
            Nullable <DateTime> asOfDate,
            string projectionRunneridentifier,
            IWriteContext writeContext = null)
        {
            EventStream qryEvents = EventStream.Create(Constants.Domain_Query,
                                                       queryName,
                                                       queryGuid.ToString());

            if (null != qryEvents)
            {
                if (null != writeContext)
                {
                    qryEvents.SetContext(writeContext);
                }

                await qryEvents.AppendEvent(new TheLongRun.Common.Events.Query.ProjectionRunStarted(
                                                domainName,
                                                aggregateTypeName,
                                                WebUtility.UrlDecode(aggregateInstanceKey),
                                                WebUtility.UrlDecode(projectionTypeName),
                                                asOfDate.GetValueOrDefault(DateTime.UtcNow),
                                                projectionRunneridentifier
                                                ));
            }
        }
        public void Call()
        {
            #region older versions without generics, code redundancy
            var numbers = new List();
            numbers.Add(2);

            var booksList = new BookList();
            booksList.Add(new Book());
            #endregion

            var numbersList = new GenericList <int>();
            numbers.Add(10);

            var books = new GenericList <Book>();
            books.Add(new Book());

            var dictionary = new GenericDictionary <string, Book>();
            dictionary.Add("1234", new Book());

            var number = new Nullable <int>(5);
            Console.WriteLine("Has value? " + number.HasValue);
            Console.WriteLine("Value: " + number.GetValueOrDefault());

            var numberTwo = new Nullable <int>();
            Console.WriteLine("Has value? " + numberTwo.HasValue);
            Console.WriteLine("Value: " + numberTwo.GetValueOrDefault());
        }
Exemple #26
0
        static void Main(string[] args)
        {
            Nullable <int> age_1      = 20;
            DateTime?      birthday_1 = null;
            int            age_2;
            DateTime       birthday_2;

            if (age_1.HasValue)
            {
                age_2 = age_1.Value;
            }
            else
            {
                age_2 = 22;
            }
            if (birthday_1 != null)
            {
                birthday_2 = (DateTime)birthday_1;
            }
            else
            {
                birthday_2 = DateTime.Parse("1990/1/1");
            }
            Console.WriteLine("年龄:{0}", age_2);
            Console.WriteLine("出生日期:{0}", birthday_2);

            age_1      = null;
            age_2      = age_1.GetValueOrDefault();
            birthday_2 = birthday_1.GetValueOrDefault();
            Console.WriteLine();
            Console.WriteLine("年龄:{0}", age_2);
            Console.WriteLine("出生日期:{0}", birthday_2);
        }
        public HttpResponseMessage Get(Nullable <int> skip, Nullable <int> take)
        {
            try
            {
                IQueryable <Community_Showcase_Category> query = dc.Community_Showcase_Categories.AsQueryable();

                // skip
                if (skip.HasValue)
                {
                    query = query.Skip(skip.GetValueOrDefault());
                }

                // take
                if (take.HasValue)
                {
                    query = query.Take(take.GetValueOrDefault());
                }

                query = query.OrderBy(i => i.name);

                List <CategoryDTO> dtos = new List <CategoryDTO>();

                foreach (Community_Showcase_Category category in query)
                {
                    CategoryDTO categoryDTO = category.ToDto();
                    dtos.Add(categoryDTO);
                }
                return(Request.CreateResponse(HttpStatusCode.OK, dtos));
            }
            catch (Exception ex)
            {
                Exceptions.LogException(ex);
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, ex));
            }
        }
Exemple #28
0
        public List <DateCountDTO> GetUsers(int portal_id, Nullable <DateTime> start_date, Nullable <DateTime> end_date)
        {
            var query = dc.Community_Visits.Where(i => i.Tab.PortalID == portal_id);

            if (start_date.HasValue)
            {
                query = query.Where(i => i.date.Date >= start_date.GetValueOrDefault().Date);
            }

            if (end_date.HasValue)
            {
                query = query.Where(i => i.date.Date <= end_date.GetValueOrDefault().Date);
            }

            var list = query.ToList();

            var results = list
                          .GroupBy(i => i.date.Date)
                          .Select(i => new DateCountDTO()
            {
                date  = i.Key,
                count = i.Select(o => o.Community_Visitor.user_id).Distinct().Count()
            })
                          .OrderBy(i => i.date)
                          .ToList();

            return(results);
        }
Exemple #29
0
        private void _ReconnectTimer(Nullable <Int32> reconnectMilliseconds)
        {
            try
            {
                lock (m_ReconnectLocker)
                {
                    if (m_ReconnectTimer != null)
                    {
                        m_ReconnectTimer.Dispose();
                        m_ReconnectTimer = null;
                    }

                    // since a reconnect will definately occur we can stop the check timers for now until reconnect succeeds (where they are recreated)
                    _KillTimers();

                    LoggerQueue.Warn(">>>>>> REDIS STARTING RECONNECT TIMER >>>>>>");

                    m_ReconnectTimer = new Timer(_Connect, false, reconnectMilliseconds.GetValueOrDefault(m_ReconnectTime), Timeout.Infinite);
                }
            }
            catch (Exception ex)
            {
                LoggerQueue.Error("Error during _ReconnectTimer", ex);
            }
        }
        static void Main(string[] args)
        {
            #region Phần 1 Null
            // ClassA classA1, classA2;
            // classA1 = new ClassA();    // classA1 tham chiếu (gán) bằng một đối tượng
            // classA2 = classA1;          // classA1, classA2 cùng tham chiếu một đối tượng
            //
            // classA1 = null;             // classA1 gán bằng null =>  không trỏ đến đối tượng nào
            // classA2.method1();         // classA2 có trỏ đến đến tượng, nên có thể truy cập các thành viên của đối tượng
            // classA1.method1();         // classA1 không trỏ đến đối tượng nào, nên truy cập thành viên sẽ lỗi
            //
            // int temp1 = 10;             //  int là kiểu tham trị, nó có thể gán giá trị cho biến temp1 (10)
            //                             //int temp2 = null;           //  lỗi - kiểu tham  trị  không được gán null hay bằng tham chiếu đến đến tượng


            #endregion
            #region Phần 2 nullable  Khi khai báo biến có khả năng nullable thì thêm vào ? sau kiểu dữ liệu
            //1. Không thể gán giá trị null cho biến kiểu int theo đúng định nghĩa
            // int temp;
            // temp 1 = null;
            int?temp2;                  //Hoặc Nullable<int> temp2;

            temp2 = null;               //Có thể gán null
            temp2 = 10;                 //Gán giá trị như biến bình thường
            if (temp2 != null)
            {
                int value = temp2.Value; //Lấy giá trị trong biến nullable
            }
            #endregion

            /*2.  NULLABLE TYPED
             + Cú pháp:
             +        - Nullable<T> tên biến;
             +        - T? tên biến;
             + Cần gán gia trị cho biến khi khai báo nếu không sẽ bị lỗi và nên kiểm tra giá tị trước khi dùng bằng HasValue
             + Dùng phương thức GetValueOrDefault() để lấy giá mặc định của kiểu dữ liệu
             + Dùng toán tử ?? thực hiện gán Nullable Type cho Non-Nullable Type
             +
             */
            Nullable <int> temp3 = null;
            Nullable <int> temp4 = 11;
            int?           temp5 = 100;
            int?[]         arr   = new int?[5];

            if (temp4.HasValue) //Kiểm tra giá trị trước dùng
            {
                Console.WriteLine(temp3.Value);
            }
            else
            {
                Console.WriteLine("Giá trị là empty");
            }
            //GetValueOrDefault() phương thức lấy giá trị mặc định của kiểu dữ liệu
            Console.WriteLine(temp3.GetValueOrDefault());//Giá trị mặc định = 0

            //Toán tử ?? thực hiện gán Nullable Type cho Non-Nullable type
            int?temp6 = null;
            int temp7 = temp6 ?? 0;//Temp7 = temp6 nếu temp6 khác null, temp7 = 0 nếu temp6 = null
        }
 /// <summary>
 /// Determines whether [is range valid] [the specified value].
 /// </summary>
 /// <param name="value">The value.</param>
 /// <param name="min">The min.</param>
 /// <param name="max">The max.</param>
 /// <returns>
 ///     <c>true</c> if [is range valid] [the specified value]; otherwise, <c>false</c>.
 /// </returns>
 public static bool IsRangeValid <T>(Nullable <T> value, T min, T max) where T : struct, IComparable, IComparable <T>
 {
     if (!value.HasValue)
     {
         return(true); //don't perform validation if no value
     }
     return(IsRangeValid(value.GetValueOrDefault(), min, max));
 }
Exemple #32
0
        public static void Example1()
        {
            Nullable <int> i = null;
            int?           j = 4;

            Console.WriteLine(i.GetValueOrDefault());     // It will print 0
            Console.WriteLine(j.GetValueOrDefault());     // It will print 4
        }
 public static string GetDoubleValueText(Nullable <double> value)
 {
     if (value == null)
     {
         return("Null");
     }
     return(value.GetValueOrDefault().ToString("F3"));
 }
Exemple #34
0
        public List <int> GetUsers(int portal_id, Nullable <DateTime> start_date, Nullable <DateTime> end_date)
        {
            var users = new List <int>();

            var query = dc.Community_Visits.Where(i => i.Tab.PortalID == portal_id);

            if (start_date.HasValue)
            {
                query = query.Where(i => i.date.Date >= start_date.GetValueOrDefault().Date);
            }

            if (end_date.HasValue)
            {
                query = query.Where(i => i.date.Date <= end_date.GetValueOrDefault().Date);
            }

            var results = query
                          .GroupBy(i => i.date.Date)
                          .Select(i => new DateCountDTO()
            {
                date  = i.Key,
                count = i.Select(o => o.Community_Visitor.user_id).Distinct().Count()
            })
                          .OrderBy(i => i.date)
                          .ToList();

            var date = start_date.GetValueOrDefault().Date;
            var end  = end_date.GetValueOrDefault().Date;

            while (date <= end)
            {
                var result = results.Where(i => i.date.Date == date.Date).SingleOrDefault();
                if (result != null)
                {
                    users.Add(result.count);
                }
                else
                {
                    users.Add(0);
                }
                date = date.AddDays(1);
            }

            return(users);
        }
Exemple #35
0
 public static Option <T> Maybe <T>(Nullable <T> value)
     where T : struct
 {
     if (!value.HasValue)
     {
         return(Option.None <T>(value.GetValueOrDefault()));
     }
     return(Option.Some <T>(value.Value));
 }
 public TalkNPCTask(int npcType, string text, string objective = null, Nullable <float> spawnIncrease = null, Nullable <int> itemReceived = null)
 {
     _npcType       = npcType;
     NPCText        = text;
     _objective     = objective;
     _spawnIncrease = spawnIncrease;
     _itemReceived  = itemReceived.GetValueOrDefault();
     hasTakenItems  = false;
 }
        //
        // GET: /Admin/ArticleType/Details/5

        public ActionResult Details(Nullable<Guid> id = null)
        {
            ArticleType articletype = ArticleTypeService.GetByKey(id.GetValueOrDefault());
            if (articletype == null)
            {
                return HttpNotFound();
            }
            return View(articletype);
        }
Exemple #38
0
    public static void Main(string[] args)
    {
        int? d = new Nullable<int>();
        int? one = 1;

        Console.WriteLine("{0} {1}", d.HasValue, one.HasValue);
        Console.WriteLine("{0} {1}", d.GetValueOrDefault(), one.GetValueOrDefault());
        Console.WriteLine("{0}", one.Value);
    }
Exemple #39
0
        public static Dictionary<string, long> GetNotifyQueueMessageData(NotifyType emailType, Nullable<long> SourceCustomerID, Nullable<long> TargetCustomerID, Nullable<long> ChallengeID)
        {
            Dictionary<string, long> data = new Dictionary<string, long>();

            data.Add("nType", (long)emailType);
            if (SourceCustomerID != null)
                data.Add("SrcID", SourceCustomerID.GetValueOrDefault());
            if(TargetCustomerID!=null)
                data.Add("TgtID", TargetCustomerID.GetValueOrDefault());
            if(ChallengeID!=null)
                data.Add("ChaID", ChallengeID.GetValueOrDefault());

            return data;
        }
        static void Main(string[] args)
        {
            var book = new Book { Isbn = "1111", Title = "C# Advanced" };

            var books = new GenericList<Book>();
            books.Add(book);

            //

            var number = new Nullable<int>();
            Console.WriteLine("Has Value ?" + number.HasValue);
            Console.WriteLine("Value: " + number.GetValueOrDefault());

        }
Exemple #41
0
        static void Main(string[] args)
        {

            //GenericList<string> cheese = new GenericList<string>();

            //cheese.Add("bacon");

            //Console.WriteLine( cheese[0]);

            //GenericDictionary<string, int> bacon = new GenericDictionary<string, int>();

            //nullable class is part of .net System.Nullable
            var number = new Nullable<int>();
            Console.WriteLine(number.HasValue);
            Console.WriteLine(number.GetValueOrDefault());
         
        }
Exemple #42
0
 public void Method() {
     int i = 10;
     bool b = true;
     bool? flag;
     int? num;
     Nullable<int> num2;
     Nullable<int> num3 = new Nullable<int>(100);
     Nullable<bool> xyz = false;
     char? ch;            
     
     bool hasValue = xyz.HasValue || num3.HasValue;
     int num3_ = num3.Value;
     bool f = flag.HasValue ? flag.Value : true;
     
     xyz = true;
     num2 = 10;
     num = 1;
     
     bool boolVal = flag.GetValueOrDefault();
     char textVal = ch.GetValueOrDefault();
     int numVal = num3.GetValueOrDefault();
 }
Exemple #43
0
 static void Main(string[] args)
 {
     var number = new Nullable<int>();
     Console.WriteLine("Has Value?" + number.HasValue);
     Console.WriteLine("Value is equal to: " + number.GetValueOrDefault());
 }
 private ArticleType GetArticleTypeInstance(Nullable<Guid> id)
 {
     ArticleType articletype = ArticleTypeService.GetByKey(id.GetValueOrDefault());
     return articletype;
 }
        internal void InitializeFrom(BindingElement bindingElement, bool initializeNestedBindings)
        {
            if (bindingElement == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("bindingElement");
            }
            SecurityBindingElement sbe = (SecurityBindingElement)bindingElement;

            // Can't apply default value optimization to properties like DefaultAlgorithmSuite because the defaults are computed at runtime and don't match config defaults
            this.DefaultAlgorithmSuite = sbe.DefaultAlgorithmSuite;
            this.IncludeTimestamp = sbe.IncludeTimestamp;
            if (sbe.MessageSecurityVersion != MessageSecurityVersion.Default)
            {
                this.MessageSecurityVersion = sbe.MessageSecurityVersion;
            }            
            // Still safe to apply the optimization here because the runtime defaults are the same as config defaults in all cases
            SetPropertyValueIfNotDefaultValue(ConfigurationStrings.KeyEntropyMode, sbe.KeyEntropyMode);
            SetPropertyValueIfNotDefaultValue(ConfigurationStrings.SecurityHeaderLayout, sbe.SecurityHeaderLayout);
            SetPropertyValueIfNotDefaultValue(ConfigurationStrings.ProtectTokens, sbe.ProtectTokens);
            SetPropertyValueIfNotDefaultValue(ConfigurationStrings.AllowInsecureTransport, sbe.AllowInsecureTransport);
            SetPropertyValueIfNotDefaultValue(ConfigurationStrings.EnableUnsecuredResponse, sbe.EnableUnsecuredResponse);


            Nullable<bool> requireDerivedKeys = new Nullable<bool>();

            if (sbe.EndpointSupportingTokenParameters.Endorsing.Count == 1)
            {
                this.InitializeNestedTokenParameterSettings(sbe.EndpointSupportingTokenParameters.Endorsing[0], initializeNestedBindings);
            }
            else if (sbe.EndpointSupportingTokenParameters.SignedEncrypted.Count == 1)
            {
                this.InitializeNestedTokenParameterSettings(sbe.EndpointSupportingTokenParameters.SignedEncrypted[0], initializeNestedBindings);
            }
            else if (sbe.EndpointSupportingTokenParameters.Signed.Count == 1)
            {
                this.InitializeNestedTokenParameterSettings(sbe.EndpointSupportingTokenParameters.Signed[0], initializeNestedBindings);
            }

            bool initializationFailure = false;

            foreach (SecurityTokenParameters t in sbe.EndpointSupportingTokenParameters.Endorsing)
            {
                if (t.HasAsymmetricKey == false)
                {
                    if (requireDerivedKeys.HasValue && requireDerivedKeys.Value != t.RequireDerivedKeys)
                        initializationFailure = true;
                    else
                        requireDerivedKeys = t.RequireDerivedKeys;
                }                
            }

            SymmetricSecurityBindingElement ssbe = sbe as SymmetricSecurityBindingElement;
            if ( ssbe != null )
            {
                SetPropertyValueIfNotDefaultValue(ConfigurationStrings.MessageProtectionOrder, ssbe.MessageProtectionOrder);
                this.RequireSignatureConfirmation = ssbe.RequireSignatureConfirmation;
                if ( ssbe.ProtectionTokenParameters != null )
                {
                    this.InitializeNestedTokenParameterSettings( ssbe.ProtectionTokenParameters, initializeNestedBindings );
                    if ( requireDerivedKeys.HasValue && requireDerivedKeys.Value != ssbe.ProtectionTokenParameters.RequireDerivedKeys )
                        initializationFailure = true;
                    else
                        requireDerivedKeys = ssbe.ProtectionTokenParameters.RequireDerivedKeys;

                }
            }
            else
            {
                AsymmetricSecurityBindingElement asbe = sbe as AsymmetricSecurityBindingElement;
                if ( asbe != null )
                {
                    SetPropertyValueIfNotDefaultValue(ConfigurationStrings.MessageProtectionOrder, asbe.MessageProtectionOrder);
                    this.RequireSignatureConfirmation = asbe.RequireSignatureConfirmation;
                    if ( asbe.InitiatorTokenParameters != null )
                    {
                        this.InitializeNestedTokenParameterSettings( asbe.InitiatorTokenParameters, initializeNestedBindings );

                        //
                        // Copy the derived key token bool flag from the token parameters. The token parameter was set from
                        // importing WSDL during SecurityBindingElementImporter.ImportPolicy time
                        //
                        if ( requireDerivedKeys.HasValue && requireDerivedKeys.Value != asbe.InitiatorTokenParameters.RequireDerivedKeys )
                            initializationFailure = true;
                        else
                            requireDerivedKeys = asbe.InitiatorTokenParameters.RequireDerivedKeys;
                    }
                }
            }

            this.willX509IssuerReferenceAssertionBeWritten = DoesSecurityBindingElementContainClauseTypeofIssuerSerial(sbe);
            this.RequireDerivedKeys = requireDerivedKeys.GetValueOrDefault(SecurityTokenParameters.defaultRequireDerivedKeys);
            this.LocalClientSettings.InitializeFrom(sbe.LocalClientSettings);
            this.LocalServiceSettings.InitializeFrom(sbe.LocalServiceSettings);

            if (!initializationFailure)
                initializationFailure = !this.TryInitializeAuthenticationMode(sbe);

            if (initializationFailure)
                this.failedSecurityBindingElement = sbe;
        }
        // GET: Department/Delete/5
        public ActionResult Delete(Nullable<Int32> id, Nullable<Boolean> concurrencyError)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Department department = db.Departments.Find(id);
            if (department == null && concurrencyError == null)
            {
                return HttpNotFound();
            }

            if (concurrencyError.GetValueOrDefault())
            {
                if (department == null)
                {
                    ViewBag.ConcurrencyErrorMessage = "The record you attempted to delete "
                        + "was deleted by another user after you got the original values. "
                        + "Click the Back to List hyperlink.";
                }
                else
                {
                    ViewBag.ConcurrencyErrorMessage = "The record you attempted to delete "
                        + "was modified by another user after you got the original values. "
                        + "The delete operation was canceled and the current values in the "
                        + "database have been displayed. If you still want to delete this "
                        + "record, click the Delete button again. Otherwise "
                        + "click the Back to List hyperlink.";
                }
            }

            return View(department);
        }